gpt4 book ai didi

JavaScript 迭代二维数组并返回不匹配项

转载 作者:行者123 更新时间:2023-11-28 04:32:28 25 4
gpt4 key购买 nike

我有两个 2D 数组,我想使用 JavaScript 比较它们,忽略匹配,如果不匹配,则将整行返回到新数组中。

    var array1 = [ ['52a1fd0296fc','DEF'],
['52a1fd0296fc','DEF'],
['52a1fd0296fc','DEF'],
['52a1fd0296fc','DEF'],
[null,'ABC'],
['6f93cfa0106f','xxx'],
];

var array2 = [ ['52a1fd0296fc','ABC'],
['6f93cfa0106f','xxx'],
['52a1fd0296fc','ABC'],
['52a1fd0296fc','ABC'],
['52a1fd0296fc','DEF'],
['52a1fd0296fcasd','DEF'], ];

我想获取此输出,即 array2 中存在而不是 array1 中存在的数组:

array3 = [['52a1fd0296fcasd','DEF'],['52a1fd0296fc','ABC']]

请问有什么想法吗?

最佳答案

只需循环两个数组:

var array1 = [ ['52a1fd0296fc','DEF'],
['52a1fd0296fc','DEF'],
['52a1fd0296fc','DEF'],
['52a1fd0296fc','DEF'],
[null,'ABC'],
['6f93cfa0106f','xxx'],
['52a1fd0296fc','ABC'] ];

var array2 = [ ['52a1fd0296fc','ABC'],
['6f93cfa0106f','xxx'],
['52a1fd0296fc','ABC'],
['52a1fd0296fc','ABC'],
['52a1fd0296fc','DEF'] ];

var array3 = [];
for(var i = 0; i<array1.length; ++i) {
var a = array1[i];
var found = false;
for(var j = 0; j<array2.length; ++j) {
var b = array2[j];
if(a[0] == b[0] && a[1] == b[1]) {
found = true;
break;
}
}
if(!found) {
array3.push(a);
}
}

console.dir(array3);

我假设您想要 array1 而没有 array2,而不是相反。

关于JavaScript 迭代二维数组并返回不匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44516492/

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