Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use [...new Set()] to get only uniques based off inner Array<object.id>?

Is it possible to use [...new Set()] to return an array of unique objects based on the inner id value? If this isn't possible, is there any other clever ES6 ways to achieve this output?

Reference: Unique Values in an Array

var arr = [
  {email: '[email protected]', id: 10}
]

var arr2 = [
  {email: '[email protected]', id: 10},
  {email: '[email protected]', id: 13}
]
mergedArray = arr.concat(arr2);

console.log(
  [...new Set(mergedArray)]
);

// output would be:
//  [
//    {email:'[email protected]', id: 10},
//    {email:'[email protected]', id: 13}
//  ]
like image 783
Armeen Harwood Avatar asked Oct 21 '25 16:10

Armeen Harwood


1 Answers

To get the unique objects based on ID, you could create a Map instead of a Set, pass it a 2-element Array as iterator, and it will have unique keys, and then get it's values

var arr = [
  {email: '[email protected]', id: 10}
]

var arr2 = [
  {email: '[email protected]', id: 10},
  {email: '[email protected]', id: 13}
]

var mergedArray = arr.concat(arr2);
var map         = new Map(mergedArray.map(o => [o.id,o]));
var unique      = [...map.values()];

console.log(unique);
like image 82
adeneo Avatar answered Oct 23 '25 05:10

adeneo



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!