[英]Javascript get result array from two input arrays
I have two arrays我有两个数组
a=[2,3 ,10, 20]
b=[true, false, false, true]
the final result should be最终结果应该是
result=[2,20]
that is a where b is true那是 a 其中 b 为真
how can do this using javascript functional programming (without for loop).如何使用 javascript 函数式编程(没有 for 循环)来做到这一点。
Array.prototype.filter() Array.prototype.filter()
The
filter()
method creates a new array with all elements that pass the test implemented by the provided function.filter()
方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。
You can use filter()
on the first array.您可以在第一个数组上使用
filter()
。 In side the callback function check the item of the current index from the second array:在回调函数中,检查第二个数组中当前索引的项目:
let a=[2,3 ,10, 20] let b=[true, false, false, true] let res = a.filter((n,i) => b[i] == true); //OR: //let res = a.filter((n,i) => b[i]); console.log(res);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.