Skip to content Skip to sidebar Skip to footer

Remove Duplicate Items From Array Of Nested Objects And Retain Their Order : Javascript

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:

Solution 1:

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));

Solution 2:

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));

Post a Comment for "Remove Duplicate Items From Array Of Nested Objects And Retain Their Order : Javascript"