JavaScript 遍历二维数组并返回不匹配项 [英] JavaScript iterate through 2D array and return the mismatches
本文介绍了JavaScript 遍历二维数组并返回不匹配项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个二维数组,我想使用 JavaScript 比较它们,忽略匹配项,如果不匹配则将整行返回到一个新数组中.
I have two 2D arrays, I want to compare them using JavaScript, ignore the matches and if there are mismatches to return the entire row into a new array.
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 中的数组:
I want to take this output, the arrays that exists in array2 and NOT in array1:
array3 = [['52a1fd0296fcasd','DEF'],['52a1fd0296fc','ABC']]
有什么想法吗?
推荐答案
您可以使用数组的连接值作为键并过滤第二个数组的一次,同时指示已插入的项.
You could use the joined values of the array as key and filter the once of the second array, while indicating already inserted items.
var array1 = [ ['52a1fd0296fc','DEF'], ['52a1fd0296fc','DEF'], ['52a1fd0296fc','DEF'], ['52a1fd0296fc','DEF'], [null,'ABC'], ['6f93cfa0106f','xxx']],
array2 = [ ['52a1fd0296fc','ABC'], ['6f93cfa0106f','xxx'], ['52a1fd0296fc','ABC'], ['52a1fd0296fc','ABC'], ['52a1fd0296fc','DEF'], ['52a1fd0296fcasd','DEF']],
hash = Object.create(null),
result;
array1.forEach(function (a) {
hash[a.join('|')] = true;
});
result = array2.filter(function (a) {
return !hash[a.join('|')] && (hash[a.join('|')] = true);
});
console.log(result);
这篇关于JavaScript 遍历二维数组并返回不匹配项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文