是否有一种方法可以在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"]
当前回答
ES2015的函数方法
计算两个数组之间的差值是Set操作之一。这个术语已经表明应该使用本机Set类型,以便提高查找速度。不管怎样,当你计算两个集合之间的差值时,有三种排列:
[+left difference] [-intersection] [-right difference]
[-left difference] [-intersection] [+right difference]
[+left difference] [-intersection] [+right difference]
下面是反映这些排列的功能性解决方案。
离开的区别:
// small, reusable auxiliary functions const apply = f => x => f(x); const flip = f => y => x => f(x) (y); const createSet = xs => new Set(xs); const filter = f => xs => xs.filter(apply(f)); // left difference const differencel = xs => ys => { const zs = createSet(ys); return filter(x => zs.has(x) ? false : true ) (xs); }; // mock data const xs = [1,2,2,3,4,5]; const ys = [0,1,2,3,3,3,6,7,8,9]; // run the computation console.log( differencel(xs) (ys) );
正确的区别:
差异是微不足道的。这与翻转的参数不同。为了方便,你可以写一个函数:const differencer = flip(difference)。这是所有!
对称的区别:
现在我们有了左边和右边,实现对称的差异也变得微不足道:
// small, reusable auxiliary functions const apply = f => x => f(x); const flip = f => y => x => f(x) (y); const concat = y => xs => xs.concat(y); const createSet = xs => new Set(xs); const filter = f => xs => xs.filter(apply(f)); // left difference const differencel = xs => ys => { const zs = createSet(ys); return filter(x => zs.has(x) ? false : true ) (xs); }; // symmetric difference const difference = ys => xs => concat(differencel(xs) (ys)) (flip(differencel) (xs) (ys)); // mock data const xs = [1,2,2,3,4,5]; const ys = [0,1,2,3,3,3,6,7,8,9]; // run the computation console.log( difference(xs) (ys) );
我想这个例子是一个很好的起点,可以让你了解函数式编程的含义:
使用可以以许多不同方式组合在一起的构建块进行编程。
其他回答
这是工作的:基本上合并两个数组,寻找重复的,并将没有重复的推入一个新数组,这是差异。
函数diff(arr1, arr2) { var newArr = []; Var arr = ar1 .concat(arr2); For (var I in arr){ Var f = arr[i]; Var t = 0; (j = 0;j < arr.length;j + +) { If (arr[j] === f){ t + +; } } 如果(t == 1){ newArr.push (f); } } 返回newArr; }
我想要一个类似的函数,它接受一个旧数组和一个新数组,并给我一个添加项的数组和一个删除项的数组,我希望它是有效的(所以没有.contains!)。
你可以在这里尝试我提出的解决方案:http://jsbin.com/osewu3/12。
有人能看出算法的问题或改进吗?谢谢!
代码清单:
function diff(o, n) {
// deal with empty lists
if (o == undefined) o = [];
if (n == undefined) n = [];
// sort both arrays (or this won't work)
o.sort(); n.sort();
// don't compare if either list is empty
if (o.length == 0 || n.length == 0) return {added: n, removed: o};
// declare temporary variables
var op = 0; var np = 0;
var a = []; var r = [];
// compare arrays and add to add or remove lists
while (op < o.length && np < n.length) {
if (o[op] < n[np]) {
// push to diff?
r.push(o[op]);
op++;
}
else if (o[op] > n[np]) {
// push to diff?
a.push(n[np]);
np++;
}
else {
op++;np++;
}
}
// add remaining items
if( np < n.length )
a = a.concat(n.slice(np, n.length));
if( op < o.length )
r = r.concat(o.slice(op, o.length));
return {added: a, removed: r};
}
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)) ]
如果你不关心原始数组,编辑它们没有问题,那么这是一个更快的算法:
let iterator = arrayA.values()
let result = []
for (entryA of iterator) {
if (!arrayB.includes(entryA)) {
result.push(entryA)
} else {
arrayB.splice(arrayB.indexOf(entryA), 1)
}
}
result.push(...arrayB)
return result
**这将根据'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' ]