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}
// ]
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With