将true/false数组与其他数组进行比较

5

最快的比较两个数组并返回第三个数组的方法是什么?新数组包含来自array2的值,其中与array1相关联的值为true

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

结果应该是:
const result = ['a', 'd'];

1
你是在问最快的方式,指的是性能方面吗? - codeherk
3个回答

7
使用 filter

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

ES5 语法:

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


1

Filter函数比for循环慢。更快的选项是使用带有或不带三元运算符的for循环。它比filter函数更快。

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


1
我对它们所有的操作都获得了0ms,并且我非常喜欢.filter的可读性... - deceze
@deceze我更喜欢“filter”的可读性;但是,OP确实要求最快的方法。在我的机器上,使用filter需要0.060ms,使用forLoopWithTernary需要0.010ms,而使用forLoopWithoutTernary也需要0.010ms。每次运行时间都会有所变化。我承认区别不大,但这正是OP要求的。 - codeherk

0
你可以使用 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');


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接