是否有一种方法可以在JavaScript中返回两个数组之间的差异?
例如:
var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];
// need ["c", "d"]
是否有一种方法可以在JavaScript中返回两个数组之间的差异?
例如:
var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];
// need ["c", "d"]
当前回答
非常简单的解决方案与JavaScript的过滤器功能:
Var a1 = ['a', 'b']; Var a2 = ['a', 'b', 'c', 'd']; (arr1, arr2) { var newArr = []; var myArr = ar1 .concat(arr2); newArr = myArr.filter(函数(项){ return arr2.indexOf(item) < 0 || arr1.indexOf(item) < 0; }); 警报(newArr); } diffArray (a1, a2);
其他回答
这个答案是2009年写的,所以有点过时了,但是对于理解这个问题还是很有教育意义的。我今天最好的解决办法是
let difference = arr1.filter(x => !arr2.includes(x));
(此处致谢给其他作者)
我假设你比较的是一个普通数组。如果不是,你需要将for循环改为for ..在循环。
函数arr_diff (a1, a2) { Var a = [], diff = []; For (var I = 0;I < a1.length;我+ +){ A [a1[i]] = true; } For (var I = 0;I < a2.length;我+ +){ If (a[a2[i]]) { 删除一个[a2[我]]; }其他{ A [a2[i]] = true; } } 对于(var k in a) { diff.push (k); } 返回差异; } console.log (arr_diff ([a, b], [a, b, c, d '))); console.log (arr_diff(“abcd”、"中的")); console.log (arr_diff(“必杀技”,“必杀技”));
如果不使用hasOwnProperty,那么我们有不正确的元素。例如:
[1,2,3].diff([1,2]); //Return ["3", "remove", "diff"] This is the wrong version
我的版本:
Array.prototype.diff = function(array2)
{
var a = [],
diff = [],
array1 = this || [];
for (var i = 0; i < array1.length; i++) {
a[array1[i]] = true;
}
for (var i = 0; i < array2.length; i++) {
if (a[array2[i]]) {
delete a[array2[i]];
} else {
a[array2[i]] = true;
}
}
for (var k in a) {
if (!a.hasOwnProperty(k)){
continue;
}
diff.push(k);
}
return diff;
}
var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];
var diff = [];
for (var i in a2) {
var found = false;
for (var j in a1) {
if (a2[i] === a1[j]) found = true;
}
if (found === false) diff.push(a2[i]);
}
那么简单。也可以用于对象,检查对象的一个属性。 就像,
if (a2[i].id === a1[j].id) found = true;
纯JavaScript解决方案(没有库) 与旧浏览器兼容(不使用过滤器) O (n ^ 2) 可选的fn回调参数,用于指定如何比较数组项
function diff(a, b, fn){ var max = Math.max(a.length, b.length); d = []; fn = typeof fn === 'function' ? fn : false for(var i=0; i < max; i++){ var ac = i < a.length ? a[i] : undefined bc = i < b.length ? b[i] : undefined; for(var k=0; k < max; k++){ ac = ac === undefined || (k < b.length && (fn ? fn(ac, b[k]) : ac == b[k])) ? undefined : ac; bc = bc === undefined || (k < a.length && (fn ? fn(bc, a[k]) : bc == a[k])) ? undefined : bc; if(ac == undefined && bc == undefined) break; } ac !== undefined && d.push(ac); bc !== undefined && d.push(bc); } return d; } alert( "Test 1: " + diff( [1, 2, 3, 4], [1, 4, 5, 6, 7] ).join(', ') + "\nTest 2: " + diff( [{id:'a',toString:function(){return this.id}},{id:'b',toString:function(){return this.id}},{id:'c',toString:function(){return this.id}},{id:'d',toString:function(){return this.id}}], [{id:'a',toString:function(){return this.id}},{id:'e',toString:function(){return this.id}},{id:'f',toString:function(){return this.id}},{id:'d',toString:function(){return this.id}}], function(a, b){ return a.id == b.id; } ).join(', ') );
基于思考者的答案,但允许重复。
映射在映射值出现时增加它们,如果它们在另一个数组中,则减少它们。
任何剩余的部分都将包括在差额中。
function diff(curr, prev) { let a = curr.split('').sort(), b = prev.split('').sort(), c = arrDiff(a, b); console.log(JSON.stringify(a), '-', JSON.stringify(b), '=', JSON.stringify(c)); return c; } function arrDiff(larger, smaller) { var entries = {}; for (var i = 0; i < larger.length; i++) { entries[larger[i]] = (entries[larger[i]] || 0) + 1; } for (var i = 0; i < smaller.length; i++) { if (entries[smaller[i]]) { entries[smaller[i]] -= 1; } else { entries[smaller[i]] = (entries[smaller[i]] || 0) + 1; } } return Object.keys(entries).sort().reduce((diff, key) => { if (entries[key] > 0) { for (var i = 0; i < entries[key]; i++) { diff.push(key); } } return diff; }, []); } // Smaller is a subset of Larger console.log('Result:', JSON.stringify(diff('ENLIGHTEN', 'LENGTHEN'))); // [ I ] console.log('Result:', JSON.stringify(diff('STRENGTH', 'TENTHS'))); // [ G, R ] // Both have a unique value console.log('Result:', JSON.stringify(diff('BUBBLE', 'RUBBLE'))); // [ B, R ] .as-console-wrapper { top: 0; max-height: 100% !important; }