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

Error: Knockout sortable array failing to render nested elements accurately

As a newcomer to Knockout.js, I have recently delved into the world of JQuery and the knockout-sortable project. My current project involves utilizing a complex data structure to present forms. Specifically, I am attempting to create a nested sortable arra ...

When trying to revert back to the original content after using AJAX to display new HTML data, the .html() function

Here is the JavaScript I am using to handle an ajax request: $(document).ready(function() { // Variable to hold original content var original_content_qty = ''; $('.product-qty-<?php echo $products->fields[' products_id ...

Retrieving the result of a callback function within a nested function

I'm struggling with a function that needs to return a value. The value is located inside a callback function within the downloadOrders function. The problem I'm encountering is that "go" (logged in the post request) appears before "close" (logged ...

When initially loaded, the Bootstrap Datepicker displays an inaccurate calendar

I implemented Bootstrap Datepicker to insert a date input field into my HTML document. Below is the code I used: HTML: <input type="text" name="manifest-date" class="calendar form-control" placeholder="M-d-yy" id="manifest-date" value="{{$currentDate} ...

What is the procedure for matching paths containing /lang using the express middleware?

I need to target paths that contain /lang? in the URL, but I am unsure how to specifically target paths that begin with /lang? I have two routes: app.get('/lang?..... app.get('/bottle/lang?....... I want to target these routes using app.use(&a ...

Learn how to access a variable within the Watch function using a directive in Angular framework

I'm new to Angular and encountering some issues with the watch function. I am trying to track changes in a variable inside a controller, and once the value of this variable changes, I want to pass that updated value to a directive. Below is the code ...

What is the best way to manage the maximum number of concurrent AJAX requests?

I am currently working on an autocomplete search bar feature. <input type="text" class="form-control" id="text" > <script> $("input").keyup(function(){ let key = $("input").val(); ...

JavaScript Tip: Effortless method to confirm the presence of duplicate values within an array

Similar Question: Best method for identifying duplicate values in a JavaScript array If I have an extensive array containing thousands of elements, I am looking to check if there are 2 or more elements with identical values and return true. I unders ...

AngularJS - how to dynamically delete a directive from an element

Looking for a way to dynamically add or remove directives from compiled and linked elements? I have a page with numerous inputs and want to disable all of them if a specific flag is set. The conventional method using jQuery's element.prop('disabl ...

React is unable to identify the property that was passed to a styled-component in Material UI

Custom Styled Component Using Material-UI: import { Typography } from '@material-ui/core'; const CustomText = styled(Typography)<TextProps>` margin-bottom: 10px; color: ${({ textColor }) => textColor ?? textColor}; font-size: ${( ...

dynamically assigning a style attribute based on the dimensions of an image retrieved from a URL

My aim is to determine whether or not I should use an image based on its dimensions. To achieve this, I came across a function on stack overflow that can retrieve the dimensions of an image just by using its URL. Here is the code snippet they provided: f ...

If the div element is present on the page, incorporate additional class and attributes to enhance its functionality

Similar Question: How to add new class and attributes to div if it exists on the page I am in search of JavaScript code that can be implemented on my master page. This code should check for the existence of a specific div, and if found, it should add ...

Executing ForceAtlas2 algorithm from a predetermined starting point within Sigma.js

I need assistance with rendering a complex network using the React-Sigma wrapper. The base structure of this network consists of numerous nodes of degree one and some nodes with high degrees. I have prepared my graph data with x and y coordinates that repr ...

Error encountered while installing Material UI in Next.js with TypeScript and pure JavaScript configurations

I'm brand new to React and Next.js, so please forgive me for asking what may seem like a silly question. I'm attempting to install Material UI in a fresh Next.js application that I created using "npx create-next-app@latest". I've been refere ...

There was an issue encountered when attempting to access the stackoverflow api

I am currently attempting to retrieve all questions tagged with ipv4 from stackoverflow using the stackoverflow API. However, I encountered the following error message: No 'Access-Control-Allow-Origin' header is present on the requested resource. ...

Exploring the integration of Nuxt runtime config variables within Jest testing

In my nuxt.config.js file, I have defined private runtime configuration settings. During my jest tests, I encountered an error when trying to test a method that uses these runtime config variables - it kept throwing an undefined variable error. Can anyon ...

Tips for executing JavaScript code within a component

Looking to incorporate a parallax effect into an HTML element in my template. Have the code written, but uncertain of where to place it so that it runs each time the page is scrolled. let pos = document.body.scrollTop; document.getElementById('parall ...

List of characteristics belonging to objects contained within an array

Consider the following array of objects: data = [{x: 1, y: 2, z: 3}, {x: 4, y: 5, z: 6}, {x: 7, y: 8, z: 9}] Is there a way to extract only the x elements from these objects and create an array out of them? For example: x = [1, 4, 7] Can this be achiev ...

What could be the reason for Vue not finishing the build process?

Screenshot of Files Second Screenshot of Files Upon creating a new project using Vue3 and Vite (v4.3.1), I encountered an issue where the npm run build command failed to compile my project correctly. While the build command appeared to be successful, wit ...

What scenarios call for utilizing "dangerouslySetInnerHTML" in my React code?

I am struggling to grasp the concept of when and why to use the term "dangerous," especially since many programmers incorporate it into their codes. I require clarification on the appropriate usage and still have difficulty understanding, as my exposure ha ...