考虑我有2个数组如下:
Array1 = ["123","234"]
Array2 = [{"keyA":"123","keyB":"rtefre"},{"keyA":"789","keyB":"sdfs"}, {"keyA":"234","keyB":"tyrvfd"}]
我必须将Array1字符串与Array2中的keyA进行比较,并获取所有这些细节。
我的结果如下:
[{"keyA":"123","keyB":"rtefre"}, {"keyA":"234","keyB":"tyrvfd"}]
我必须尽可能避免使用For循环。请分享您的想法。提前谢谢。
答案 0 :(得分:2)
怎么样
filteredArray = Array2.filter(item => Array1.indexOf(item.KeyA) !== -1);
另外,假设它在节点中运行,我假设你可以访问这里使用的一些es6细节(箭头函数和原生过滤器)
答案 1 :(得分:0)
您可以使用哈希表并过滤项目。
var array1 = ["123", "234"],
array2 = [{ "keyA": "123", "keyB": "rtefre" }, { "keyA": "789", "keyB": "sdfs" }, { "keyA": "234", "keyB": "tyrvfd" }],
hash = Object.create(null),
result;
array1.forEach(a => hash[a] = true);
result = array2.filter(a => hash[a.keyA]);
console.log(result);
答案 2 :(得分:0)
如果要考虑效果,那么您应该避免indexOf
并做一些比这更聪明的事情......即:排序Array1
并执行二进制搜索< /强>
我建议使用javascript对象。 所以解决方案如下......
var Array1 = ["123","234"]
var Array2 = [{"keyA":"123","keyB":"rtefre"},
{"keyA":"789","keyB":"sdfs"},
{"keyA":"234","keyB":"tyrvfd"}]
var map=Array1.reduce(function(prev,current){
prev[current]=true;
return prev;
},{});//Creating object to find out if the element exist or not
Array2 = Array2.filter(function(item){
return !!map[item["keyA"]];//filtering elements which are not in map.
});
console.log(Array2);