gpt4 book ai didi

javascript - 如何在javascript中的数组中添加非重复对象?

转载 作者:行者123 更新时间:2023-11-30 07:55:41 25 4
gpt4 key购买 nike

我想将非重复对象添加到新数组中。

var array = [
{
id: 1,
label: 'one'
},
{
id: 1,
label: 'one'
},
{
id: 2,
label: 'two'
}
];

var uniqueProducts = array.filter(function(elem, i, array) {
return array.indexOf(elem) === i;
});

console.log('uniqueProducts', uniqueProducts);
// output: [object, object, object]

live code

最佳答案

我喜欢使用 es6 的基于类的方法。该示例使用 lodash 的 _.isEqual 方法来确定对象的相等性。

var array = [{
id: 1,
label: 'one'
}, {
id: 1,
label: 'one'
}, {
id: 2,
label: 'two'
}];

class UniqueArray extends Array {
constructor(array) {
super();
array.forEach(a => {
if (! this.find(v => _.isEqual(v, a))) this.push(a);
});
}
}

var unique = new UniqueArray(array);
console.log(unique);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>

关于javascript - 如何在javascript中的数组中添加非重复对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40303637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com