Determine distinct items in an array that match a predefined criteria

I have a list of objects with two keys, img1 and img2. I need to identify unique objects based on the values of img1, while also retaining the corresponding value of img2.

This is the current code I am using:

const imgs_arr = [
    ...new Set(
      input_arr.map(item => {img_1: item.img1[0]})
    )
  ];
  return imgs_arr;

Input Array:

[{img1: ['/path/to/img1'], img2: ['/path/to/img2']},
{img1: ['/path/to/img1'], img2: ['/path/to/img3']},
{img1: ['/path/to/img1'], img2: ['/path/to/img4']},
{img1: ['/path/to/img12'], img2: ['/path/to/img5']},
{img1: ['/path/to/img12'], img2: ['/path/to/img46']},
{img1: ['/path/to/img12'], img2: ['/path/to/img45']},
{img1: ['/path/to/img12'], img2: ['/path/to/img478']}]

Expected Output Array:

[{img1: '/path/to/img1', img2: '/path/to/img2'},
{img1: '/path/to/img12', img2: '/path/to/img5'}]

To provide more context to the question, the goal is to find unique values for img1 and then retrieve the corresponding value for img2 from the first instance.

Your assistance is greatly appreciated!

Answer №1

Implement a forEach loop to create an object with unique keys. Retrieve the values using Object.values.

const data = [
  { img1: ["/path/to/img1"], img2: ["/path/to/img2"] },
  { img1: ["/path/to/img1"], img2: ["/path/to/img3"] },
  { img1: ["/path/to/img1"], img2: ["/path/to/img4"] },
  { img1: ["/path/to/img12"], img2: ["/path/to/img5"] },
  { img1: ["/path/to/img12"], img2: ["/path/to/img46"] },
  { img1: ["/path/to/img12"], img2: ["/path/to/img45"] },
  { img1: ["/path/to/img12"], img2: ["/path/to/img478"] }
];

const update = data => {
  const res = {};

  data.forEach(item => {
    const u_key = item.img1[0];
    if (!(u_key in res)) {
        res[u_key] = item;
    }
  });
  return Object.values(res);
};

console.log(update(data));

Answer №2

function filterArrayByImg1(arr) {

  let uniqueImages = [];

  return arr.filter((element, index) => {

      if (!element.img1 || !element.img1[0] || uniqueImages.includes(element.img1[0]))
        return false;
      else {
        uniqueImages.push(element.img1[0]);
        return true;
      }
    })
    .map(element => ({
      img1: element.img1[0],
      img2: element.img2[0]
    }));
}


let inputImages = [{
    img1: ['/path/to/img1'],
    img2: ['/path/to/img2']
  },
  {
    img1: ['/path/to/img1'],
    img2: ['/path/to/img3']
  },
  {
    img1: ['/path/to/img1'],
    img2: ['/path/to/img4']
  },
  {
    img1: ['/path/to/img12'],
    img2: ['/path/to/img5']
  },
  {
    img1: ['/path/to/img12'],
    img2: ['/path/to/img46']
  },
  {
    img1: ['/path/to/img12'],
    img2: ['/path/to/img45']
  },
  {
    img1: ['/path/to/img12'],
    img2: ['/path/to/img478']
  }
];

// Filter the array for unique images
let filteredImages = filterArrayByImg1(inputImages);

console.log(filteredImages);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can we dynamically showcase a table column/row containing data with varying sizes of nested arrays?

I am struggling to showcase the data retrieved from firestore on a table using Vue.js and Element UI. Most solutions I found are for displaying a fixed amount of data, but my case involves an uneven number of data entries. Here is the structure of my data ...

How can we compress videos on an Android device prior to uploading them through a web browser?

Can video compression be done prior to uploading via a web browser? For example, in iOS devices you can choose a video using the HTML input type file tag and iOS will automatically compress it before uploading. Are there any JavaScript or jQuery libraries ...

Having difficulty displaying elements from two arrays at particular intervals

I am currently working with two arrays that have the same number of items in each. My goal is to print these items in intervals within the console. The desired output would look something like this: 1 Bruce Wayne 45 Then, after a one-second interval, it s ...

The concept of matryoshka logic applied to data manipulation

"mainData"{ entities:[] }, "data2":{ entities:[ { name:"mainData": //entites }, { name:"mainData": //entites }, { name:"m ...

Is there a way to launch my JavaScript project locally and have index.html served on an npm server?

I am currently attempting to launch a specific Single Page Application (SPA) project using pure JavaScript. This project consists of a script file and an index.html file. I am trying to run this project on my local machine, but it requires that it be hos ...

How can I activate a function or pass a selected value to a different scope variable using AngularUI Bootstrap Datepicker?

Check out this AngularUI Datepicker demo on Plunker: http://plnkr.co/edit/DWqgfTvM5QaO5Hs5dHco?p=preview I'm curious about how to store the selected value in a variable or trigger another function when a date is chosen in the field. I couldn't ...

Vue transition isn't functioning correctly without the specified mode parameter of 'out-in'

I'm struggling to comprehend why the transition doesn't smoothly roll from top to bottom without mode="out-in". When using out-in, it rolls as expected (albeit with a delay), but without it, the transition just suddenly appears after rolling dow ...

Toggle Visibility of Div Based on Matching Class Name When Clicked

Just delving into the world of jQuery and could use some guidance. Is there a way to show a div with a matching class when a specific button is clicked? For example, clicking on a button with the class '.project1' should display the corresponding ...

How to incorporate a JavaScript file into a Handlebars template

I am having trouble receiving calls to my JavaScript file. What could be the issue? Using MVC. Here is the code in view file, file.hbs: <div class="container"> <h2 onClick="test()">Title</h2> {{>list}} </div> <script sr ...

What is the best way to transfer information from df ~ to my webpage?

I'm currently working on a pie chart that visualizes the disk space usage on my Linux machine. I need help figuring out how to properly parse this data onto a microservice URL. Any assistance would be greatly appreciated. Here's what I have so f ...

Styling a modal popup using session storage in CSS

I recently created a modal popup using CSS by following a helpful tutorial that can be found at this link: Now, I am curious about how to store the value entered in a textbox as session data. I came across some code in another tutorial that demonstrated h ...

The operation of 'val' is not supported by HTMLInputElement

While working with a table row, I am iterating through each cell. Inside every cell lies a text box containing some value that I need to store in an array. function dothing() { var tds = $('#'+selected+' td'); var submi ...

Enrollment of Vue components

After importing the component into the JavaScript file, I added it to the index.vue file as follows: import fmsSubUnitDetails from '../subunitDetails'; export default{ components: { fmsSubUnitDetails }, } Despite this, I am still encount ...

Exploring AngularJS: A closer look at ngOptions expressions

I have been struggling to populate a Select element with a list of objects for ngOptions. Despite confirming that the data structure is correct and accessible, I cannot get the Select to show the options. Even when rendering the options expression on the p ...

Having issues with AJAX and button submit while trying to upload a file using Flask

I've been attempting to incorporate a file upload feature (specifically a .csv file) using bootstrap, and then submit it by clicking on a button. I've experimented with various methods to implement the file upload functionality, but haven't ...

The value of type 'X' cannot be assigned to type 'Y' or 'undefined'

In my code, there is a component that requires a prop with an enum value: export enum AType { some = "SOME", word = "WORD", } const MyComponent = (arg: AType) => {} When I try calling this component like so: <MyComponent ar ...

The JSON array retrieved from the $http.GET request is coming back as undefined, which is not expected

Presenting my code below: function gatherDataForGraph(unit, startTs, endTs, startState, endState){ points = []; console.log('/file/tsDataPoints/'+unit+"?startDate="+startTs+"&endDate="+endTs+"&startState="+startState+"&endState="+en ...

Set a maximum height for an image without changing its width dimension

I am facing an issue with an image displayed in a table. The image is a graph of profiling information that can be quite tall (one vertical pixel represents data from one source, while one horizontal pixel equals one unit of time). I would like to set a ma ...

Trouble with Vue images not displaying

I'm encountering an issue with displaying images in my Vue CLI project. Here's the situation: this particular Vue file is accessing a JSON file that contains references to individual Eyewear objects, which is all functioning correctly. The JSON ...

Is there a way to retrieve the request URL within the validate function of the http strategy?

Is it possible to access the context object present in guards within the validate method of my bearer strategy, by passing it as an argument along with the token? bearer-auth.guard.ts: @Injectable() export class BearerAuthGuard extends AuthGuard('be ...