是否有一种方法可以在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解决方案(没有库) 与旧浏览器兼容(不使用过滤器) 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(', ') );
其他回答
如果你有两个对象列表
const people = [{name: 'cesar', age: 23}]
const morePeople = [{name: 'cesar', age: 23}, {name: 'kevin', age: 26}, {name: 'pedro', age: 25}]
let result2 = morePeople.filter(person => people.every(person2 => !person2.name.includes(person.name)))
试一试。
var first = [ 1, 2, 3, 4, 5 ];
var second = [ 4, 5, 6 ];
var difference = first.filter(x => second.indexOf(x) === -1);
console.log(difference);
Output: [ 1, 2, 3]
Var first = [1,2,3,4,5]; Var second = [4,5,6]; Var差=第一。filter(x => second.indexOf(x) === -1); console.log(差异);
function diffArray(newArr, oldArr) {
var newSet = new Set(newArr)
var diff = []
oldArr.forEach((a) => {
if(!newSet.delete(a))diff.push(a)
})
return diff.concat(Array.from(newSet))
}
修正了一下最佳答案
function arr_diff(a1, a2)
{
var a=[], diff=[];
for(var i=0;i<a1.length;i++)
a[a1[i]]=a1[i];
for(var i=0;i<a2.length;i++)
if(a[a2[i]]) delete a[a2[i]];
else a[a2[i]]=a2[i];
for(var k in a)
diff.push(a[k]);
return diff;
}
这将考虑当前的元素类型。B /c当我们创建一个[a1[i]]时,它将一个值从原始值转换为字符串,因此我们失去了实际值。
如果你想找出两个object数组之间的差异,你可以这样做:
let arrObj = [{id: 1},{id: 2},{id: 3}] let arrObj2 = [{id: 1},{id: 3}] let result = arrObj。filter(x => arrObj2.)每个(x2 => x2。Id == x.id) console.log(结果)