Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get missing objects from 2 arrays of objects

let selected = [
  {id: 15, name: 'Canada'},
  {id: 25, name: 'Germany'}
];

let all = [
  {id: 15, name: 'Canada'},
  {id: 25, name: 'Germany'},
  {id: 32, name: 'United States'},
  {id: 40, name: 'China'}
]

How do I get non-selected countries from all objects and print it out in another variable? Based on id key of those which are in selected array?

like image 559
knitevision Avatar asked May 19 '26 16:05

knitevision


1 Answers

You need to find all objects that aren't contained in selected and then do something with them:

let nonSelectedItems = all.filter(obj => selected.every(s => s.id !== obj.id));

//do stuff with non-selected items
like image 60
tymeJV Avatar answered May 22 '26 04:05

tymeJV



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!