是否有一种方法可以在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"]
当前回答
数据:
var new_storage = JSON.parse('[{"id_order":"0003"},{"id_order":"0004"},{"id_order":"0006"}]');
var old_storage = JSON.parse('[{"id_order":"0001"},{"id_order":"0002"},{"id_order":"0003"},{"id_order":"0004"},{"id_order":"0005"}]');
使用过滤器:
var diff = new_storage
.filter(x => {if(!(old_storage.filter(y => y.id_order==x.id_order)).length){return x}})
.concat(old_storage
.filter(x => {if(!(new_storage.filter(y => y.id_order==x.id_order)).length){return x}})
)
console.log(JSON.stringify(diff))
两个数组的结果不同
[{"id_order":"0006"},{"id_order":"0001"},{"id_order":"0002"},{"id_order":"0005"}]
其他回答
求两个没有重复项的数组的差值:
function difference(arr1, arr2){
let setA = new Set(arr1);
let differenceSet = new Set(arr2.filter(ele => !setA.has(ele)));
return [...differenceSet ];
}
1.difference([2,2,3,4],[2,3,3,4])将返回[]
2.difference([1,2,3],[4,5,6])将返回[4,5,6]
3.difference([1,2,3,4],[1,2])返回[]
4.difference([1,2],[1,2,3,4])将返回[3,4]
注意:上述解决方案要求始终将较大的数组作为第二个参数发送。要找到绝对差值,首先需要找到两者的较大数组,然后对它们进行处理。
求两个不存在重复项的数组的绝对差值:
function absDifference(arr1, arr2){
const {larger, smaller} = arr1.length > arr2.length ?
{larger: arr1, smaller: arr2} : {larger: arr2, smaller: arr1}
let setA = new Set(smaller);
let absDifferenceSet = new Set(larger.filter(ele => !setA.has(ele)));
return [...absDifferenceSet ];
}
1. absdifference((2, 2, 3, 4),[2、3、3、4])将返回[]
2. absdifference([1, 2, 3],[4、5、6])将返回(4、5、6)
3. absdifference([1、2、3、4],[1,2])将返回(3、4)
4. absdifference([1, 2],[1、2、3、4])将返回(3、4)
请注意这两个解决方案中的示例3
function diff(arr1, arr2) {
var filteredArr1 = arr1.filter(function(ele) {
return arr2.indexOf(ele) == -1;
});
var filteredArr2 = arr2.filter(function(ele) {
return arr1.indexOf(ele) == -1;
});
return filteredArr1.concat(filteredArr2);
}
diff([1, "calf", 3, "piglet"], [1, "calf", 3, 4]); // Log ["piglet",4]
function arrayDiff(a, b) {
return a.concat(b).filter(val => !(b.includes(val)));
//(or) return a.concat(b).filter(val => !(a.includes(val) && b.includes(val)));
}
以下是我使用的方法:
var newArr = a1.filter(function(elem) {
return a2.indexOf(elem) === -1;
}).concat( a2.filter(function(elem) {
return a1.indexOf(elem) === -1;
}));
console.log(newArr);
或者这个
var newArr = a1.concat(a2);
function check(item) {
if (a1.indexOf(item) === -1 || a2.indexOf(item) === -1) {
return item;
}
}
return newArr.filter(check);
这是我用来获得两个数组之间的差异的函数-它适用于数值,字符串,混合num/字符串数组。在数组/多维数组中不是对象文字
function diff(arr1, arr2) {
var x,
t;
function uniq(a, b) {
t = b;
if( (b === 0 && x[b+1]!==a) ||
(t > 0 && a !== x[b+1] && a !== x[b-1]) ) {
return a;
}
}
x = arr1.concat(arr2).sort();
return x.filter(uniq);
}
var a1 = ['a', 'b', 'e', 'c'],
a2 = ['b', 'a', 'c', 'f' ];
diff(a1, a2);