[英]Filter an array of objects based on array property containing all values from another array
[英]array to filtered based on all values in another array
我正在努力实现以下目标:
使用两个第一个数组的交集创建一个新数组
给予:
array1: [{ 'id': 2, 'detail': 2 },
{ 'id': 4, 'detail': 5}]
array2:[{ 'no': 1},
{ 'no': 4,},
{'no' : 7}]
生成:
array3: [{ 'id': 4, 'detail': 5}]
Because array1.id = array2.no
任何对此的更简洁代码的建议
您可以通过查找所需的id
/ no
来过滤数组。
var array1 = [{ id: 2, detail: 2 }, { id: 4, detail: 5 }], array2 = [{ no: 1 }, { no: 4 }, { no: 7 }], result = array1.filter(function (a) { return array2.some(function (b) { return a.id === b.no; }) }); console.log(result);
带Set
ES6进行查找。
var array1 = [{ id: 2, detail: 2 }, { id: 4, detail: 5 }], array2 = [{ no: 1 }, { no: 4 }, { no: 7 }] no = new Set(array2.map(o => o.no)), result = array1.filter(o => no.has(o.id)); console.log(result);
从这里开始: 在角度js中显示两个数组的交集
function(arr1, arr2){
return arr1.filter(function(n) {
return arr2.indexOf(n) != -1
});
}
let arr1 = [{ 'id': 2, 'detail': 2 }, { 'id': 4, 'detail': 5 }]; let arr2 = [{ 'no': 1 }, { 'no': 4, }, { 'no': 7 }]; let result=arr1.filter(function(x){ for(let i in arr2){ if(arr2[i].no==x.id) return true } return false; }); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.