Compare true/false array with other array

Viewed 97

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'];
3 Answers

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');

Related