是否有一种方法可以在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"]
当前回答
function array_diff(array1, array2) {
let returnArray = [];
$.each(array1, function(index, value) {
let findStatus = false;
if (Array.isArray(array2)) {
$.each(array2, function(index2, value2) {
if (value == value2) findStatus = true;
});
} else {
if (value == array2) {
findStatus = true;
}
}
if (findStatus == false) {
returnArray.push(value);
}
});
return returnArray;
}
其他回答
在这种情况下,您可以使用Set。它针对这种操作(并、交、差)进行了优化。
确保它适用于你的案例,一旦它不允许重复。
var a = new JS.Set([1,2,3,4,5,6,7,8,9]);
var b = new JS.Set([2,4,6,8]);
a.difference(b)
// -> Set{1,3,5,7,9}
所选的答案只对了一半。您必须比较数组的两种方式才能得到完整的答案。
const ids_exist = [
'1234',
'5678',
'abcd',
]
const ids_new = [
'1234',
'5678',
'efjk',
'9999',
]
function __uniq_Filter (__array_1, __array_2) {
const one_not_in_two = __array_1.filter(function (obj) {
return __array_2.indexOf(obj) == -1
})
const two_not_in_one = __array_2.filter(function (obj) {
return __array_1.indexOf(obj) == -1
})
return one_not_in_two.concat(two_not_in_one)
}
let uniq_filter = __uniq_Filter(ids_exist, ids_new)
console.log('uniq_filter', uniq_filter) // => [ 'abcd', 'efjk', '9999' ]
ES6中一个更简洁的方法是以下解决方案。
var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];
区别
a2.filter(d => !a1.includes(d)) // gives ["c", "d"]
十字路口
a2.filter(d => a1.includes(d)) // gives ["a", "b"]
析取联合(对称差分)
[ ...a2.filter(d => !a1.includes(d)),
...a1.filter(d => !a2.includes(d)) ]
下面是另一个可以返回差异的解决方案,就像git diff一样:(它已经用typescript编写,如果你不使用typescript版本,只需删除类型)
/**
* util function to calculate the difference between two arrays (pay attention to 'from' and 'to'),
* it would return the mutations from 'from' to 'to'
* @param { T[] } from
* @param { T[] } to
* @returns { { [x in string]: boolean } } it would return the stringified version of array element, true means added,
* false means removed
*/
export function arrDiff<T>(from: T[], to: T[]): { [x in string]: boolean } {
var diff: { [x in string]: boolean } = {};
var newItems: T[] = []
diff = from.reduce((a, e) => ({ ...a, [JSON.stringify(e)]: true }), {})
for (var i = 0; i < to.length; i++) {
if (diff[JSON.stringify(to[i])]) {
delete diff[JSON.stringify(to[i])]
} else {
newItems.push(to[i])
}
}
return {
...Object.keys(diff).reduce((a, e) => ({ ...a, [e]: false }), {}),
...newItems.reduce((a, e) => ({ ...a, [JSON.stringify(e)]: true }), {})
}
}
下面是一个用法示例:
arrDiff(['a', 'b', 'c'], ['a', 'd', 'c', 'f']) //{"b": false, "d": true, "f": true}
function diffArray(arr1, arr2) {
const newArr = [];
// arr1 match to arr2
arr1.map((item)=>{
if(arr2.indexOf(item)<0){
console.log(item)
newArr.push(item)
}
})
// arr2 match to arr1
arr2.map((item)=>{
if(arr1.indexOf(item)<0){
newArr.push(item)
}
})
return newArr;
}
差异([1,2,3,5],[1,2,3,4,5])
输出::[4]