0

I have

array1 = [{ name: sample1 }, { name: sample2 }, { name: sample3 }];
array2 = [{ name: sample1 }, { name: sample2 }];

I want to filter objects of array1 which exists in array2. So I need to have

[{ name: sample1 }, { name: sample2 }]

How can I get it in javascript?

ShawnOrr
  • 1,249
  • 1
  • 12
  • 24
Atousa Darabi
  • 847
  • 1
  • 7
  • 26
  • What have you tried so far ? Can you please share your attempt to get the results you are after! – Always Helping Feb 06 '22 at 20:19
  • I thought I can do it by filter. `const array = array1.filter(item => array2.includes(item)).` But it didn't work – Atousa Darabi Feb 06 '22 at 20:24
  • Does `array2` contain references of the same object that are in `array1` OR its different objects but with same structure? – Som Shekhar Mukherjee Feb 06 '22 at 20:24
  • @SomShekharMukherjee it has same objects – Atousa Darabi Feb 06 '22 at 20:25
  • Is every object guaranteed to contain only one key called `name`? If not, do you care about the existence of other keys? – kmoser Feb 06 '22 at 20:28
  • So should I check each key in filter too, you mean? – Atousa Darabi Feb 06 '22 at 20:29
  • if you only have one key called `name` in both arrays. you could do something like this to get the results are you are after -> `const arrr = arr1.filter(item => arr2.some(o2 => item.name === o2.name));` – Always Helping Feb 06 '22 at 20:34
  • it is more than 20 key @AlwaysHelping – Atousa Darabi Feb 06 '22 at 20:34
  • 1
    Please edit your question to includes all the information you have. So thats its clear for all of us. We should be not going back and forth to get basic info about the question. Add all the info before posting. – Always Helping Feb 06 '22 at 20:37
  • @AlwaysHelping sure, thanks for comment. – Atousa Darabi Feb 06 '22 at 20:39
  • Does this answer your question? [How to get the intersection of two sets while recognizing equal set values/items not only by reference but by their equal structures and entries too?](https://stackoverflow.com/questions/71015428/how-to-get-the-intersection-of-two-sets-while-recognizing-equal-set-values-items) – Peter Seliger Feb 09 '22 at 10:02

2 Answers2

0

You can use .filter and .some function in JavaScript , Here is the example

const array1 = [{ name: "sample1" }, { name: "sample2" }, { 
name: "sample3" }];
 const array2 = [{ name: "sample1" }, { name: "sample2" }];
let Result = array1.filter(function(obj) {
  return array2.some(function(obj2) {
    return obj.name== obj2.name;
});
}); 
console.log(Result)
Zeeshan
  • 174
  • 10
0

You can use object destructuring, the map() and .includes() methods as shown below:

const array1 = [{ name: "sample1" }, { name: "sample2" }, { name: "sample3" }];
const array2 = [{ name: "sample1" }, { name: "sample2" }];

const filtered = array1.filter(
    ({name}) => array2.map(o => o.name).includes(name)
);

console.log( filtered );
PeterKA
  • 24,158
  • 5
  • 26
  • 48