要求
写一个 function,传入两个或两个以上的数组,返回一个以给定的原始数组排序的不包含重复值的新数组。
换句话说,所有数组中的所有值都应该以原始顺序被包含在内,但是在最终的数组中不包含重复值。
非重复的数字应该以它们原始的顺序排序,但最终的数组不应该以数字顺序排序。
样本
unite([1, 3, 2], [5, 2, 1, 4], [2, 1]) 应该返回 [1, 3, 2, 5, 4]。
unite([1, 3, 2], [1, [5]], [2, [4]]) 应该返回 [1, 3, 2, [5], [4]]。
unite([1, 2, 3], [5, 2, 1]) 应该返回 [1, 2, 3, 5]。
unite([1, 2, 3], [5, 2, 1, 4], [2, 1], [6, 7, 8]) 应该返回 [1, 2, 3, 5, 4, 6, 7, 8]。
参考
解法
function unite(arr1, arr2, arr3) {
for(var i=1;i<arguments.length;i++){
arguments[i].reduce(function(accumulator,currentValue){
if(!arr1.includes(currentValue)) arr1.push(currentValue);
},0);
}
return arr1;
}
unite([1, 3, 2], [5, 2, 1, 4], [2, 1]);
注意!如果没有提供 initialValue,那么accumulator取数组中的第一个值,currentValue取数组中的第二个值。

本文介绍了一个JavaScript函数,该函数能够接受多个数组作为参数,并返回一个新的数组。这个新数组包含了所有输入数组中的元素,同时去除了重复项,并保持了原始数组中元素的顺序。
1万+

被折叠的 条评论
为什么被折叠?



