gpt4 book ai didi

采用多维数组和单个数组的 JavaScript 函数,并在多维数组中查找单个数组的匹配项

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:12:39 26 4
gpt4 key购买 nike

我试着在堆栈溢出中查看类似的问题,但它并没有完全迎合我正在尝试做的事情,我一直试图让它工作,但不断得到错误的结果。在这一点上,我简直不知所措。我的意思的例子

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

关于采用多维数组和单个数组的 JavaScript 函数,并在多维数组中查找单个数组的匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42180396/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com