1 回答
![?](http://img1.sycdn.imooc.com/54584f3100019e9702200220-100-100.jpg)
TA贡献1807条经验 获得超9个赞
如果我理解正确的话,你想要找到的区别arr1和arr2,并返回该差异(如有的话)的项目(即要么是数组中的不同)的一个新的数组。
有多种方法可以实现这一点。一种方法如下:
function diffArray(arr1, arr2) {
const result = [];
const combination = [...arr1, ...arr2];
/* Obtain set of unique values from each array */
const set1 = new Set(arr1);
const set2 = new Set(arr2);
for(const item of combination) {
/* Iterate combined array, adding values to result that aren't
present in both arrays (ie exist in one or the other, "difference") */
if(!(set1.has(item) && set2.has(item))) {
result.push(item);
}
}
return result;
}
console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]), " should be [4]");
console.log(diffArray([1, 2, 3, 5, 8], [1, 2, 3, 5]), " should be [8]");
console.log(diffArray([1, 2, 3, 5, 8], [1, 2, 3, 5, 9]), " should be [8, 9]");
console.log(diffArray([1, 2], [1, 2]), " should be []");
添加回答
举报