Matthew Harwood Matthew Harwood - 1 month ago 10
Javascript Question

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: 'matthew@gmail.com', id: 10}
]

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

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

// output would be:
// [
// {email:'matthew@gmail.com', id: 10},
// {email:'matthew@gmail.com', id: 13}
// ]




Answer

You'd have to map out the ID's first, so you have an array of ID's, then you could pass those ID's to a Set and get only unique values, and spread it back to an array

var arr = [
  {email: 'matthew@gmail.com', id: 10}
]

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

console.log(
    [...new Set(mergedArray.map(o => o.id))]
);