JavaScript函数,它接受多维数组和单个数组,并在多维数组中查找单个数组的匹配项

我尝试在堆栈溢出中查看类似的问题,但它不能满足我正在尝试做的事情,并且我一直在尝试使其工作但不断得到错误的结果.在这一点上,我只是不知所措.我的意思的例子

var masterArray = [[1,2,5,6],[5,13,7,8],[9,11,13,15],[13,14,15,16],[1,9,11,12]]
var compareArray = [9,11,13,15,1,2,5,6]

function intersect(a, b) {
//code to compare both arrays and find a match
}

console.log(Intersect(compareArray, masterArray)) 

输出就是

[9,11,13,15]
[1,2,5,6]
[5,13]
[13,15]

最佳答案 使用
Array.prototype.reduce获取所有交叉点的数组,如下所示:

var masterArray = [[1,2,5,6],[5,13,7,8],[9,11,13,15],[13,14,15,16],[1,9,11,12]];
var compareArray = [9,11,13,15,1,2,5,6];


function intersect(multi, simple) {
  return multi.reduce(function(res, b) {
    var intersection = simple.reduce(function(r, e) { // get the intersection of the current array and compareArray (simple)
      if(b.indexOf(e) != -1) // if the current element of the current array is also in the compareArray then push it into the intersection array
        r.push(e);
      return r;
    }, []);
    
    res.push(intersection); // push the intersection array into the result array
    return res;
  }, []);
}

console.log(intersect(masterArray, compareArray));
点赞