匹配两个javascript数组以形成交集结果

时间:2017-04-04 11:15:11

标签: javascript jquery

找到交叉点的速记和最佳方法是什么?

f = ["A","B","C","D","E","F"]; //might be less than 8
b = [1,0,0,1,0,0,0,0];   //always 8 elements 

所需的结果数组[“A”,“D”]

5 个答案:

答案 0 :(得分:4)

您可以使用Array#filter

var f = ["A", "B", "C", "D", "E", "F"],
    b = [1, 0, 0, 1, 0, 0, 0, 0],
    r = f.filter((_, i) => b[i]);

console.log(r);

答案 1 :(得分:2)

假设您的f数组永远不会超过b数组

f.filter((item, index) => b[index] === 1);

如果您想要完全简写,可以重命名itemindex并放弃=== 1

f.filter((a, i) => b[i]);



var f = ["A","B","C","D","E","F"]; //might be less than 8
var b = [1,0,0,1,0,0,0,0];   //always 8 elements
console.log(f.filter((a, i) => b[i]));




答案 2 :(得分:1)

var f = ["A","B","C","D","E","F"];
var b = [1,0,0,1,0,0,0,0];

var res = f.filter(function(e, i) {
  return b[i]; // short for return b[i] === 1;
});

console.log(res);

甚至更短时间使用箭头功能,如下所示:

var f = ["A","B","C","D","E","F"];
var b = [1,0,0,1,0,0,0,0];

var res = f.filter((e, i) => b[i]);

console.log(res);

答案 3 :(得分:0)

另一种方式:



$(function(){
  f = ["A","B","C","D","E","F"];
  b = [1,0,0,1,0,0,0,0];
  x = [];
  $.each(b,function(key, value){
    value?x.push(f[key]):'';
  });
  console.log(x)
});




答案 4 :(得分:0)

因为for循环比filter方法快,我建议:

var results = [];
for(var i=0;i<b.length;i++){
    if (b[i]) results.push(f[i]);
}