Sto*_*ace 5 javascript arrays ecmascript-6
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'];
Run Code Online (Sandbox Code Playgroud)
The result should be:
const result = ['a', 'd'];
Run Code Online (Sandbox Code Playgroud)
Use filter.
const array1 = [true, false, false, true];
const array2 = ['a', 'b', 'c', 'd'];
const res = array2.filter((_, i) => array1[i]);
console.log(res);Run Code Online (Sandbox Code Playgroud)
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);Run Code Online (Sandbox Code Playgroud)