5

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'];
1
  • 1
    are you asking for the quickest way as in performance? Commented Jun 19, 2019 at 8:38

3 Answers 3

7

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

2 Comments

I get 0ms for all of them, and I greatly prefer the readability of .filter
@deceze I prefer the readability of filter as well; however, the OP did ask for the quickest way. On my end, I get 0.060ms for filter, 0.010ms for forLoopWithTernary, and 0.010ms for forLoopWithoutTernary. The time do change on each run.. Not much of difference I admit, but it is as OP requested.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.