简体   繁体   中英

Compare true/false array with other array

What is the quickest way to compare two arrays and return a third array containing the values from array2 where the associated values from array1 are true ?

const array1 = [true, false, false, true];
const array2 = ['a', 'b', 'c', 'd'];

The result should be:

const result = ['a', 'd'];

Use filter .

 const array1 = [true, false, false, true]; const array2 = ['a', 'b', 'c', 'd']; const res = array2.filter((_, i) => array1[i]); console.log(res); 

ES5 syntax:

 var array1 = [true, false, false, true]; var array2 = ['a', 'b', 'c', 'd']; var res = array2.filter(function(_, i) { return array1[i]; }); console.log(res); 

Filter function is slower than for loop. The quicker option is to use for loop with or without ternary operator.. It is faster than the filter function.

I've include a code snippet that shows how long each option takes.

 const array1 = [true, false, false, true]; const array2 = ['a', 'b', 'c', 'd']; // filter console.time('filter'); const result1 = array2.filter((_, i) => array1[i]); console.timeEnd('filter'); console.log(result1); // for loop with ternary operator console.time('forLoopWithTernary'); const result2 = []; for(let i = 0; i < array2.length; i++){ (array1[i]) ? result2.push(array2[i]) : null; } console.timeEnd('forLoopWithTernary'); console.log(result2); // for loop w/o ternary operator console.time('forLoopWithoutTernary'); const result3 = []; for(let i = 0; i < array2.length; i++){ if(array1[i]) result3.push(array2[i]); } console.timeEnd('forLoopWithoutTernary'); console.log(result3); 

You can use array.reduce :

 var array1 = [true, false, false, true]; var array2 = ['a', 'b', 'c', 'd']; console.time('reduce'); var res = array1.reduce((total, currentValue, index) => { return currentValue ? [...total, array2[index]] : total; }, []); console.log(res); console.timeEnd('reduce'); 

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