[英]Remove everything from Array which is not in other Array with one common field
我有两个数组,像这样:
a = [
{"id": "peter", "age": "25"},
{"id": "dave", "age": "34"},
{"id": "jack", "age": "28"}];
b = [{"id": "peter", "profession": "engineer"}];
现在,我需要做的是根据"id"
从数组a
删除不在b
的所有内容,因此“ dave”和“ jack”都需要执行。 如何有效地做到这一点? 数组之间唯一的公共字段是id
字段。
您可以像这样在数组上使用filter()
,
a = [ {"id": "peter", "age": "25"}, {"id": "dave", "age": "34"}, {"id": "jack", "age": "28"}]; b = [{"id": "peter", "profession": "engineer"}, {"id": "dave", "profession": "engineer"}]; filter = b.map(function(person) { return person.id; }) filteredArray = a.filter(function(person) { return filter.indexOf(person.id) > -1; }) console.log(filteredArray)
如果b
不太大,请构建字典以加快查找速度:
var bDict = {};
b.forEach(function (person) {
bDict[person.id] = 1;
});
然后使用filter
删除条目:
filtered = a.filter(function (person) {
return bDict[person.id];
});
此方法使用向后循环。 之所以倒退是因为splice()
删除元素时,某些对象可能会被跳过。 例如,有3人具有索引0
, 1
和2
。 如果拼接索引1
,则数组的长度现在为2,并且存在循环而无需检查第三人称。
var a = [ {"id": "peter", "age": "25"}, {"id": "dave", "age": "34"}, {"id": "jack", "age": "28"}]; var b = [{"id": "peter", "profession": "engineer"}]; function removeExtra() { for (var i = a.length - 1; i >= 0; i--) { var contained = false; b.forEach(function(be) { if (be.id === a[i].id) { contained = true; } }); if (!contained) { a.splice(i, 1); } } } removeExtra(); console.log(a);
var duplicateId=[];
b.forEach(function(e){
duplicateId.push(e.id);
});
a.filter(function (e){
return (duplicateId.indexOf(e.id)===-1)
});
console.log(a);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.