是否有一种方法可以在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 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]
其他回答
**这将根据'type'参数为任意2个数组返回一个唯一值数组,或一个重复值数组,或一个非重复值数组(difference)。**
let json1 = ['one', 'two']
let json2 = ['one', 'two', 'three', 'four']
function uniq_n_shit (arr1, arr2, type) {
let concat = arr1.concat(arr2)
let set = [...new Set(concat)]
if (!type || type === 'uniq' || type === 'unique') {
return set
} else if (type === 'duplicate') {
concat = arr1.concat(arr2)
return concat.filter(function (obj, index, self) {
return index !== self.indexOf(obj)
})
} else if (type === 'not_duplicate') {
let duplicates = concat.filter(function (obj, index, self) {
return index !== self.indexOf(obj)
})
for (let r = 0; r < duplicates.length; r++) {
let i = set.indexOf(duplicates[r]);
if(i !== -1) {
set.splice(i, 1);
}
}
return set
}
}
console.log(uniq_n_shit(json1, json2, null)) // => [ 'one', 'two', 'three', 'four' ]
console.log(uniq_n_shit(json1, json2, 'uniq')) // => [ 'one', 'two', 'three', 'four' ]
console.log(uniq_n_shit(json1, json2, 'duplicate')) // => [ 'one', 'two' ]
console.log(uniq_n_shit(json1, json2, 'not_duplicate')) // => [ 'three', 'four' ]
对我来说,把它作为部分函数处理比较容易。很惊讶没有看到函数式编程的解决方案,这是我在ES6中的:
const arrayDiff = (a, b) => {
return diff(b)(a);
}
const contains = (needle) => (array) => {
for (let i=0; i < array.length; i++) {
if (array[i] == needle) return true;
}
return false;
}
const diff = (compare) => {
return (array) => array.filter((elem) => !contains(elem)(compare))
}
var arrayDifference = function(arr1, arr2){
if(arr1 && arr1.length){
if(arr2 && arr2.length > 0){
for (var i=0, itemIndex; i<arr2.length; i++){
itemIndex = arr1.indexOf(arr2[i]);
if(itemIndex !== -1){
arr1.splice(itemIndex, 1);
}
}
}
return arr1;
}
return [];
};
arrayDifference([1,2,3,4,5], [1,5,6]);
我同意@luis-sieira的解决方案
我创建了位自解释函数,便于初学者一步一步理解:
function difference(oneArr, twoArr){
var newArr = [];
newArr = oneArr.filter((item)=>{
return !twoArr.includes(item)
});
console.log(newArr)
let arr = twoArr.filter((item)=>{
return !oneArr.includes(item)
});
newArr = newArr.concat(arr);
console.log(newArr)
}
difference([1, 2, 3, 5], [1, 2, 3, 4, 5])
如果你想找出两个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(结果)