在我的代码中,我创建了一个名为 array1 的数组。在这个数组中,我列出了多个对象。我想过滤掉 array1 对象的值作为唯一值,并且需要将 id 与其各自的值分组。我在这里添加了我的代码,
数组1
var array1 = [
{
value:"A",
id:1
},
{
value:"B",
id:1
},
{
value:"C",
id:2
},
{
value:"B",
id:5
},
{
value:"A",
id:2
},
{
value:"A",
id:1
}
];
我想要的结果,
[
{
group:"A",
groupIds:[1, 2]
},
{
group:"B",
groupIds:[1, 5]
},
{
group:"C",
groupIds:[2]
}
]
最佳答案
在纯 Javascript 中,您可以使用哈希表和 Array#indexOf
对于唯一值。
var array = [{ value: "A", id: 1 }, { value: "B", id: 1 }, { value: "C", id: 2 }, { value: "B", id: 5 }, { value: "A", id: 2 }, { value: "A", id: 1 }],
grouped = array.reduce(function (hash) {
return function (r, a) {
if (!hash[a.value]) {
hash[a.value] = { group: a.value, groupIds: [] };
r.push(hash[a.value]);
}
if (hash[a.value].groupIds.indexOf(a.id) === -1) {
hash[a.value].groupIds.push(a.id);
}
return r;
};
}(Object.create(null)), []);
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 如何从javascript中的数组中删除重复对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41395872/