简体   繁体   中英

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

how can do this using javascript functional programming (without for loop).

Array.prototype.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

You can use filter() on the first array. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM