我有两个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']]
请问好吗?
答案 0 :(得分:0)
只需遍历两个数组:
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);
&#13;
我假设你想要array1而不是array2,而不是相反。
答案 1 :(得分:0)
您可以使用数组的连接值作为键,并过滤第二个数组的一次,同时指示已插入的项目。
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);
答案 2 :(得分:0)
这是我的目标,可能更紧凑(并使用ES6)
此代码从主数组中删除重复的数组。
var array1 = [ ['52a1fd0296fc','DEF'],
['52a1fd0296fc','DEF'],
['52a1fd0296fc','DEF'],
['52a1fd0296fc','DEF'],
[null,'ABC'],
['6f93cfa0106f','xxx'],
['52a1fd0296fc','ABC'] ];
let array3 = []
array1.forEach( a1 => {
if(!array3.find(a2 => a2[0]===a1[0] && a2[1]===a1[1])) array3.push(a1)
})
console.log(array3)