如何改进和缩短以下比较两个数组并返回它们之间的对称差异的算法? [英] How could I improve and shorten the following algorithm which compares two arrays and returns the symmetric discrepancies in between them?
问题描述
我已经在这个社区的一些帮助下创建了这个函数,我想知道我的 if
语句是否可以缩短或改进,因为我还是 JS 的新手并且可以打开改进这个函数我新的知识.
I have created this function, with some assistance in this community and I would like to know if my if
statements could be shortened or improved as I am still new to JS and refining this function could open me to new knowledge.
请看下面的代码:
let jo = [1,2,3,5,6]
let ji = [1,2,3,5,4]
const checker = (arr1, arr2) => {
return arr1.every(num => arr2.includes(num)) == false &&
arr2.every(num => arr1.includes(num)) == false ?
Array.from(new Set(arr1.filter(x => !new Set(arr2).has(x))))
.concat(Array.from(new Set(arr2.filter(x => !new Set(arr1).has(x))))) :
arr1.every(num => arr2.includes(num)) == false?
Array.from(new Set(arr1.filter(x => !new Set(arr2).has(x)))) :
arr2.every(num => arr1.includes(num)) == false ?
Array.from(new Set(arr2.filter(x => !new Set(arr1).has(x)))) :
"no discrepancies"
}
console.log(checker(jo, ji));
推荐答案
由于您实际操作的是集合而不是数组,因此最好显式使用 Set
对象.首先,让我们定义几个原语:
Since you actually operate on sets and not arrays, it's better to use Set
objects explicitly. First, let's define a couple of primitives:
// A U B
let union = (a, b) => new Set([...a, ...b]);
// A \ B
let complement = (a, b) => new Set([...a].filter(x => !b.has(x)));
那么,对称差分运算可以简单地
then, the symmetric difference operation can be simply
// A d B = (A \ B) U (B \ A)
let difference = (a, b) => union(complement(a, b), complement(b, a))
如果你需要你的 check
函数来接受和返回数组,你可以这样定义:
If you need your check
function to accept and return arrays, you can define it like this:
let check = (a, b) => [...difference(new Set(a), new Set(b))]
FWIW,这是一个带有基本集合操作的小型库":
FWIW, here's a small "library" with basic set operations:
const
_set = x => x instanceof Set ? x : set.from(x),
_has = s => Set.prototype.has.bind(_set(s)),
_array = x => Array.isArray(x) ? x : [...x],
_not = f => x => !f(x),
_empty = s => s.size === 0,
_everyfn = fns => x => fns.every(f => f(x));
const set = {};
set.from = x => new Set(x);
set.of = (...args) => set.from(args);
set.union = (...args) => set.from(args.map(_array).flat());
set.intersection = (a, ...rest) => set.from(_array(a).filter(_everyfn(rest.map(_has))));
set.complement = (a, b) => set.from(_array(a).filter(_not(_has(b))));
set.difference = (a, b) => set.union(set.complement(a, b), set.complement(b, a));
set.includes = (a, b) => _empty(set.complement(b, a));
// examples:
console.log(...set.union('abc', 'abxy', 'abz'))
console.log(...set.intersection('abc', 'abxy', 'abz'))
console.log(...set.complement('abcd', 'abxy'))
console.log(...set.difference('abcd', 'abxy'))
console.log(set.includes('abcd', 'ac'))
console.log(set.includes('abcd', 'ax'))
这篇关于如何改进和缩短以下比较两个数组并返回它们之间的对称差异的算法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!