问题
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'], ];
I want to take this output, the arrays that exists in array2 and NOT in array1:
array3 = [['52a1fd0296fcasd','DEF'],['52a1fd0296fc','ABC']]
Any idea please?
回答1:
Just loop over both arrays:
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);
I assume you want array1 without array2 and not the other way around.
回答2:
Here's my go at it, maybe more compact (and using ES6)
This code removes duplicate arrays from the main array.
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)
回答3:
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);
来源:https://stackoverflow.com/questions/44516492/javascript-iterate-through-2d-array-and-return-the-mismatches