是否有一种方法可以在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"]
当前回答
困难的方法(如果你想做一些比.indexOf更奇特的东西)
var difference = function (source, target) {
return source.reduce(function (diff, current) {
if (target.indexOf(current) === -1) {
diff.push(current);
}
return diff;
}, []);
}
简单的方法
var difference = function (source, target) {
return source.filter(function (current) {
return target.indexOf(current) === -1;
});
}
其他回答
数据:
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"}]
const dbData = [{name:'ally'},
{name:'James'}]
const localData = [{name:'James'}]
const diff = dbData.filter(a =>!localData.some(b => { return a.name === b.name}))
const difference = function (baseArray, arrayToCampare, callback = (a, b) => a!== b) {
if (!(arrayToCampare instanceof Array)) {
return baseArray;
}
return baseArray.filter(baseEl =>
arrayToCampare.every(compareEl => callback(baseEl, compareEl)));
}
这就是我如何得到两个数组的不同。纯净干净。
它将返回一个包含[add list]和[remove list]的对象。
function getDiff(past, now) {
let ret = { add: [], remove: [] };
for (var i = 0; i < now.length; i++) {
if (past.indexOf(now[i]) < 0)
ret['add'].push(now[i]);
}
for (var i = 0; i < past.length; i++) {
if (now.indexOf(past[i]) < 0)
ret['remove'].push(past[i]);
}
return ret;
}
function array_diff(a, b) {
let array = [];
for(let i = 0; i <a.length; i++) {
let k = 0;
for( let j = 0; j < b.length; j++) {
if(a[i]!==b[j]) {
k++;
}
if(k===b.length) {
array = array.concat(a[i]);
}
}
if(b.length ===0) {
array = array.concat(a[i]);
}
}
return array;
}