Reputation: 3483
I need to remove the duplicate items from an array without harming their order. Please Consider this array of data
var array = [ { person: { amount: [1,1] } },
{ person: { amount: [1,1] } },
{ person: { amount: [2,1] } },
{ person: { amount: [1,2] } },
{ person: { amount: [1,2] } }];
I understand that it can be done by using new Set([iterable]) but can't work with this array. If anyone have an idea, please help. Thanks in advance.
Upvotes: 2
Views: 2505
Reputation: 41893
Double usage of Array#map
, but allows you to avoid Object.values()
which is supported only by Chrome and Firefox.
var arr = [
{ person: { amount: [1,1] } },
{ person: { amount: [1,1] } },
{ person: { amount: [2,1] } },
{ person: { amount: [1,2] } },
{ person: { amount: [1,2] } }
], res = [...new Set(arr.map(v => JSON.stringify(v)))].map(v => JSON.parse(v));
console.log(JSON.stringify(res));
Upvotes: 1
Reputation: 350365
You could convert the elements to JSON and use those as keys for a Map, and then convert that back to an array (now with update suggested by Nina Scholz):
var array = [
{ person: { amount: [1,1] } },
{ person: { amount: [1,1] } },
{ person: { amount: [2,1] } },
{ person: { amount: [1,2] } },
{ person: { amount: [1,2] } }
];
var result = [...new Map(array.map( o => [JSON.stringify(o), o])).values()];
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
A Map maintains the order in which items are added to it, so the original order is not altered by this process.
You could do it also with an intermediate Set instead of a Map, but then you need to reconstruct the objects from JSON, which limits the functionality when you have some non-key properties in your objects that are not JSON compatible (like functions):
var result = Array.from(new Set(array.map( o => JSON.stringify(o))), s => JSON.parse(s));
Upvotes: 5