[英]How to remove duplicates objects from array in javascript?
In my code i have created one array called array1. 在我的代码中,我创建了一个名为array1的数组。 In this array i have listed multiple objects.
在这个数组中,我列出了多个对象。 I want to filter out array1 objects values as unique and need to group ids with their respective values.
我想将array1对象值过滤为唯一,并需要将ID与其各自的值进行分组。 I have added my code here,
我在这里添加了我的代码,
Array1 数组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
}
];
the result which i want, 我想要的结果,
[
{
group:"A",
groupIds:[1, 2]
},
{
group:"B",
groupIds:[1, 5]
},
{
group:"C",
groupIds:[2]
}
]
In plain Javascript, you could use a hash table and Array#indexOf
for unique values. 在普通的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; }
You can use forEach()
to group objects by values and Set()
to remove duplicate ids from groupIds
您可以使用
forEach()
按值对对象进行分组,使用Set()
从groupIds
删除重复的ID
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}] var result = []; array1.forEach(function(e) { if(!this[e.value]) (this[e.value] = {group: e.value, groupIds: []}) && result.push(this[e.value]) this[e.value].groupIds = [...new Set(this[e.value].groupIds.concat(e.id))] }, {}) console.log(result)
_.uniqBy(objects, function (object) {
return object.id;
});
that will do :) 那会:)
use _.groupBy
and _.mapValues
to iterate object values 使用
_.groupBy
和_.mapValues
迭代对象值
var res = _.chain(array1)
.groupBy('value')
.mapValues(function(val, key) {
return {
group: key,
groupIds: _.chain(val).map('id').uniq().value()
};
})
.values()
.value();
Here's another in plain Javascript. 这是普通Javascript中的另一个。
var hash = {}
array1.forEach( function(e) {
hash[e.value] = hash[e.value] || [];
if (hash[e.value].indexOf(e.id) == -1) { hash[e.value].push(e.id) }
})
var result = Object.keys(hash).map( function(key) {
return { group: key, groupIds: hash[key] }
})
Using lodash: 使用lodash:
_(array1)
.uniqWith(_.isEqual)
.groupBy('value')
.map((v, k) => ({ group: k, groupIds: _.map(v, 'id')}))
.value()
id
and the value
props are compared. id
和value
props。 value
property. value
属性。 Since there are three unique values in the initial array, this object should have three keys. group
and groupIds
properties. group
和groupIds
属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.