我需要删除所有重复的元素,例如:
var arr = [
{'seriesIndex':1,pointIndex:0},
{'seriesIndex':1,pointIndex:1},
{'seriesIndex':0,pointIndex:0},
{'seriesIndex':1,pointIndex:0},
{'seriesIndex':1}
]
如何从数组中删除冗余(重复)数组对象?
我的预期输出是:
arr = [
{'seriesIndex':1,pointIndex:0},
{'seriesIndex':1,pointIndex:1},
{'seriesIndex':0,pointIndex:0},
{'seriesIndex':1}
]
如何实现这一目标?
答案 0 :(得分:2)
在vanilla Javascript中,我建议在.reduce()
方法中迭代列表时跟踪遇到的复合键。 prv.key[key]
上的测试是O(1)(哈希表查找),因此该算法为O(n)。
var arr = [
{seriesIndex:1, pointIndex:0},
{seriesIndex:1, pointIndex:1},
{seriesIndex:0, pointIndex:0},
{seriesIndex:1, pointIndex:0},
{seriesIndex:1}
];
arr = arr.reduce(function(prv, cur) {
var key = cur.seriesIndex + '/' + cur.pointIndex;
if(!prv.key[key]) {
prv.key[key] = true;
prv.res.push(cur);
}
return prv;
}, {key: {}, res: []}).res;
console.log(arr);
答案 1 :(得分:1)
答案 2 :(得分:0)
Object.prototype.compare()
的发明你可能会喜欢这个
Object.prototype.compare = function(o){
var ok = Object.keys(this);
return typeof o === "object" && ok.length === Object.keys(o).length ? ok.every(k => this[k] === o[k]) : false;
};
var arr = [{'seriesIndex':1,pointIndex:0},
{'seriesIndex':1,pointIndex:1},
{'seriesIndex':0,pointIndex:0},
{'seriesIndex':1,pointIndex:0},
{'seriesIndex':1}
],
result = arr.reduce((res,obj) => res.length === 0 ? res.concat(obj)
: !!res.find(o => obj.compare(o)) ? res
: res.concat(obj),[]);
console.log(JSON.stringify(result,null,2));