[英]Compare values in two arrays using Iterator in Javascript?
I know how to compare values in two arrays using 2 for loops however I was looking for something a bit more sophisticated like creating an iterator to iterate through one of the arrays and passing the other array to map
method . 我知道如何使用2 for循环比较两个数组中的值,但是我正在寻找更复杂的东西,例如创建一个迭代器以迭代一个数组并将另一个数组传递给
map
方法。 Is that even possible? 那有可能吗?
I'm doing a small program for class which takes an array and x arguments
and I currently have extracted the values from the arguments. 我正在为一个使用数组和x
arguments
类做一个小程序,目前我已从参数中提取了值。
function dest(arr){
var args =[];
for(var i = 1; i < arguments.length; i++){
args.push(arguments[i]);
}
return args;
}
console.log(dest([1, 2, 3, 4], 4, 4));
Now, how could I do the iterator part to compare the values inside arr
and args
? 现在,我该如何做迭代器部分来比较
arr
和args
内部的值? Thanks for the help. 谢谢您的帮助。
The result should be the results that match from both arr
and args
. 结果应该是
arr
和args
都匹配的结果。
You can use the built in filter method 您可以使用内置的过滤器方法
var arr = [2, 3, 4, 5, 6];
var args = [3, 5, 6, 7];
var result = arr.filter(function(element) {
return args.indexOf(element) > -1;
});
This will filter out all the elements out that are not present in both arrays. 这将滤除两个数组中都不存在的所有元素。 The result is a new array that contains only the matching values [3, 5, 6].
结果是一个仅包含匹配值[3、5、6]的新数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.