-1

I want to compare two arrays

array1=["123',"456"];
array2=[{id":"001",name:"prashant"},{id:"123",name:"jhh"},{id:"123444",name"baak"},{id:"456",name"sxs"}];

my objective is to extract the objects from array2 whose ids match the values in array1.

Can someone help me with the optimal solution?

Cid
  • 14,968
  • 4
  • 30
  • 45
viswanath
  • 11
  • 6
  • Does this answer your question? [Simplest code for array intersection in javascript](https://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript) – AZ_ Jan 28 '20 at 09:43
  • 2
    What have you tried so far? – cнŝdk Jan 28 '20 at 09:43
  • The intersection code is for two arrays with a similar structure. Please look at my two arrays. the structure is different – viswanath Jan 28 '20 at 09:46
  • that's even one step lesser than having both arrays of objects. – AZ_ Jan 28 '20 at 09:47
  • Also possible duplicate: [How to remove object from array except matching value?](//stackoverflow.com/q/58127808) – Nick Parsons Jan 28 '20 at 09:48
  • I extracted id's into a different array and then compared it that works. However I feel this can be optimised as this is a very crude method and can be optimised. – viswanath Jan 28 '20 at 09:49
  • yes it can be if you convert your first array into a `Set`. then the method `array.includes` of `O(n)` will be changed to `Set.has` `O(1)` – AZ_ Jan 28 '20 at 09:51

1 Answers1

2

First of all your second array (array2) is syntactically invalid.

You can try with Array.prototype.filter() and Array.prototype.includes()

var array1=["123","456"]; 
var array2 = [{id:"001",name:"prashant"},{id:"123",name:"jhh"},{id:"123444",name:"baak"},{id:"456",name:"sxs"}];

var res = array2.filter(i => array1.includes(i.id));
console.log(res);
Mamun
  • 66,969
  • 9
  • 47
  • 59