Remove duplicate items from array of nested objects and retain their order : javascript

匿名 (未验证) 提交于 2019-12-03 08:33:39

问题:

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.

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


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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!