我要在数组中已经存在带有no的对象时将其推入数组中。 我在下面尝试过,但是它提供了冗余值(全部打印)
var array=[
{id:124, value:"a", name:"e"},
{id:124, value:"b", name:"f"},
{id:125, value:"c", name:"g"},
{id:126, value:"d", name:"h"}
];
var newarray= array.reduce(function (a, b) {
if (a.indexOf(b.id) == -1) {
a.push(b)
}
return a;
}, []);
console.log(newarray);
答案 0 :(得分:1)
indexOf
在这里不起作用,因为您正在检查对象数组中字符串的存在。您可以这样使用some
或every
:
var newarray= array.reduce(function (a, b) {
if (!a.some(function(obj) { return obj.id == b.id; })) == -1) {
a.push(b)
}
return a;
}, []);
reduce
的另一种解决方案是使用filter
/ findeIndex
组合删除重复项:
var newarray= array.filter(function (o, i) {
return array.findIndex(function(obj) {
obj.id == o.id;
}) == i;
});
可以使用箭头功能将其缩短:
var newarray= array.filter((o, i) =>
array.findIndex(obj => obj.id == o.id) == i
);
示例:
var array= [
{id:124, value:"a", name:"e"},
{id:124, value:"b", name:"f"},
{id:125, value:"c", name:"g"},
{id:126, value:"d", name:"h"}
];
var newarray= array.filter((o, i) =>
array.findIndex(obj => obj.id == o.id) == i
);
console.log(newarray);
答案 1 :(得分:0)
在检查对象数组是否包含基元时,indexOf
测试没有意义:请使用.every
检查以确保累加器中的每个项目都没有匹配的ID :
var array=[
{id:124, value:"a", name:"e"},
{id:124, value:"b", name:"f"},
{id:125, value:"c", name:"g"},
{id:126, value:"d", name:"h"}
];
var newarray= array.reduce(function (a, b) {
if (a.every(item => item.id !== b.id)) {
a.push(b)
}
return a;
}, []);
console.log(newarray);
或者,为提高性能,在推入累加器时,还向外部变量(可能是Set
)添加ID:
var array=[
{id:124, value:"a", name:"e"},
{id:124, value:"b", name:"f"},
{id:125, value:"c", name:"g"},
{id:126, value:"d", name:"h"}
];
var ids = new Set();
var newarray = array.reduce((a, b) => {
if (!ids.has(b.id)) {
ids.add(b.id);
a.push(b);
}
return a;
}, []);
console.log(newarray);