Comparing arrays of objects to filter against each other?

customerItems: [
  {
    label: "itemA",
    serialNumber: 123
  },
  {
    label: "testItem",
    serialNumber: 44
  }
]

otherItems: [
  {
    label: "anotherItem",
    serialNumber: 44
  },
  {
    label: "testItem",
    serialNumber: 21
  }
]

I am interested in looping through customerItems, which is an array of objects. My goal is to filter the customerItems based on whether their serial number matches an item in another array of objects called otherItems. For instance, the desired result in this case should be:

  {
    label: "testItem",
    serialNumber: 44
  }

since otherItems has a matching serialNumber of 44.

I considered iterating through otherItems and creating an array of serial numbers, then looping through that using forEach, but I feel like there may be a more efficient way to achieve this.

Answer №1

First, create a new indexed Set containing the values to use for filtering. This Set will be based on the id property from the otherProducts array. Then, apply this Set to filter the customerProducts array.

const customerProducts = [{name: "foo", id: 123}, {name: "test", id: 44}]

const otherProducts = [{name: "other", id: 44}, {name: "test", id: 21}]

const otherProductIds = new Set(otherProducts.map(({ id }) => id))

const filteredCustomerProducts = customerProducts.filter(({ id }) =>
  otherProductIds.has(id))

console.info(filteredCustomerProducts)

Answer №2

To achieve this, utilize the array functions filter and some.

customerProducts.filter((x)=> otherProducts.some(y=> y.id === x.id));

Explanation: The filter function iterates over each element in the otherProducts array and checks if the id of customerProduct exists in otherProducts for at least one element.

Answer №3

Create two JS array variables named customerProducts and otherProducts. Implement the JS Array functions filter and find to manipulate the arrays.

let customerProducts = [
  {
    name: "foo",
    id: 123
  },
  {
    name: "test",
    id: 44
  }
]

let otherProducts = [
  {
    name: "other",
    id: 44
  },
  {
    name: "test",
    id: 21
  }
];

let filtered = customerProducts.filter( el => otherProducts.find( e => e.id == el.id) )

console.log(filtered);

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

Restrict the character count in Vue Material chips

Currently, I am utilizing the Vue Material Chips component to gather string arrays. My goal is to limit the character length of each string within the array to 30 characters. The component offers a md-limit prop which restricts the number of strings in th ...

What could be the reason for my Node.js Express response coming back as empty?

While working on a registration system, I have encountered an issue. When errors occur in the form, I receive the correct error messages. However, when a user with the same email attempts to register and triggers 'res.json({error: 'email exists& ...

Is Socket.io exclusive to browsers?

Similar Question: Using socket.io standalone without node.js How to run socket.io (client side only) on apache server My website is hosted on a Linux server with shared hosting. Since I don't have the ability to install node.js, I am looking ...

Webpage video stalling due to buffering

Currently, I am developing personalized video controls and have integrated a @progress event to monitor the video buffering progress and adjust the width of a progress bar div: <video @progress="videoBuffer($event)"> videoBuffer(e) { if ...

Learn the process of transmitting JSON data from a server-side (nodejs) to the client-side using Ajax

I have successfully set up a Node.js/express server to make a GET call to an API, which returns JSON data. Now, I am looking for ways to send this JSON data to my local JavaScript (client-server) in order to manipulate it by looping through and appending i ...

What is the method for creating an array of strings in VueJS?

In my VueJS and Vuetify project, I am working on creating a modal that allows users to input strings into a text field. What I aim to achieve is adding the inputted string to an array when the user clicks on create button. For example, if I enter 'inp ...

Custom filtering in jqGrid with an integrated filtering toolbar

Hey there! I'm currently using the latest version of jqGrid and I was curious if it's possible to implement local filtering with custom rules. In the past, I had to manually add this feature because the version I was using didn't support it. ...

Issue with disabling checkboxes in jsTree

Currently utilizing the latest version of jsTree in one of my applications. I would like to have specific checkboxes disabled by default. To achieve this, I am referencing this resource. The jstree code I am using is as follows: $("#"+"div_"+aspectid).js ...

The issue of elements flickering while being hidden and shown with jQuery has been observed in both Chrome and

Having trouble with a simple animation using jQuery? While it may work smoothly in Firefox, you might be experiencing flickering in Chrome and Edge. Check out this jsfiddle for reference: HTML <div id="boxes-wrapper"> <div class="box"></ ...

Could use some help with configuring express routes with parameters

Greetings! I am new to working with Express and I am currently in the process of creating a portfolio website. In my project, I have a Pug file named project.pug which includes HTML content that should dynamically render based on the ID of each project sto ...

React-dropzone experiencing delays in loading new files for readers

Is there a way to handle conditional responses from an API and assign the desired value to errorMessageUploaded? I'm looking for a solution to receive error messages from the API, but currently, the errormessageupload variable is not being set withou ...

Populate HTML form with return values using jQuery AJAX

I am struggling with retrieving values from jQuery/AJAX and displaying them in an HTML form within the index.php file. This is what my index.php looks like: <script type="text/javascript"> $(document).ready(function () { $('#display'). ...

AngularJS version 1.2.0 is experiencing an issue where the $http service is not properly sending requests

Why is AngularJS 1.2.0 $http not sending requests in $eval? Here is the code you can refer to: http://jsbin.com/oZUFeFI/3/watch?html,js,output ...

Transferring the selected radio button from one HTML page to another without using PHP

I'm looking to transfer radio button data from the first HTML to the second using Pure JavaScript Feel free to use jQuery if needed. jQuery was used 1st HTML <body> <label for="1"> <input type="radio" name="num" id="1" checked="che ...

jQuery sidebar with a fixed position

Is there a way to implement a sidebar menu feature using jQuery that reappears on the left as the user scrolls down the page? You can see an example sidebar menu here. ...

Issue with making requests across origins in Vuejs using axios

Currently, I am utilizing Vuejs and axios for handling web requests. So far, I have successfully managed to perform GET, POST, and PUT operations. However, the new challenge that I am facing is uploading media to the server. The server necessitates sending ...

Generate a custom image using a pre-existing background image and text using JavaScript, then save it as a JPEG file in

Managing multiple fanpages on Facebook can be quite a task, especially when it comes to posting images with funny text. I have different backgrounds for each page, which means I have to save each image individually with the text. To streamline this process ...

Unable to retrieve the array from the JSON data

Hey there, I'm currently working on parsing JSON data ** { "message": "gradeExam.php", "id": "171", "student_id": "dfd", "questions": [{ "question_id": "0", "student_input": "def doubly_" }, { ...

Deactivating a Vue custom filter when hovering over it

I'm trying to figure out how to disable a truncate filter when hovering over an element using VueJS 2. Here's the part of my template that includes the filter: <div class="eng" @mouseover="showAll">{{ word.english | truncate }}</div> ...

What is the best way to incorporate a state variable into a GraphQL query using Apollo?

My current challenge involves using a state as a variable for my query in order to fetch data from graphQl. However, I'm encountering an issue where the component does not read the state correctly. Any suggestions on how to solve this? class usersSc ...