2

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.

Suhail Mumtaz Awan
  • 3,295
  • 8
  • 43
  • 77
  • 2
    please add the wanted result. what means *duplicate*? – Nina Scholz May 10 '17 at 12:56
  • Possible duplicate of http://stackoverflow.com/questions/9229645/remove-duplicates-from-javascript-array – Sagar May 10 '17 at 12:57
  • 2
    You can clearly try something before posting this – Weedoze May 10 '17 at 12:57
  • Possible duplicate of [Remove duplicates from an array of objects in javascript](http://stackoverflow.com/questions/2218999/remove-duplicates-from-an-array-of-objects-in-javascript) – Pugazh May 10 '17 at 12:59
  • i thinks this question is different, i needed to maintain the order, and if you look at it you'll see, before posting possible duplicate links. – Suhail Mumtaz Awan May 10 '17 at 13:04

2 Answers2

5

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));
trincot
  • 317,000
  • 35
  • 244
  • 286
1

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));
kind user
  • 40,029
  • 7
  • 67
  • 77