JS合并多个数组去重算法

时间:2021-01-16 19:56:17
var arr1 = ['a','b'];
var arr2 = ['a','c','d'];
var arr3 = [1,'d',undefined,true,null];

//合并两个数组,去重
var concat_ = function(arr1,arr2){
//不要直接使用var arr = arr1,这样arr只是arr1的一个引用,两者的修改会互相影响
var arr = arr1.concat();
//或者使用slice()复制,var arr = arr1.slice(0)
for(var i=0;i<arr2.length;i++){
arr.indexOf(arr2[i]) === -1 ? arr.push(arr2[i]) : 0;
}
return arr;
}

//合并多个数组,去重
var concat = function(arr1,arr2,arr3){
if(arguments.length <= 1){
return false;
}
var concat_ = function(arr1,arr2){
var arr = arr1.concat();
for(var i=0;i<arr2.length;i++){
arr.indexOf(arr2[i]) === -1 ? arr.push(arr2[i]) : 0;
}
return arr;
}
var result = concat_(arr1,arr2);
for(var i=2;i<arguments.length;i++){
result = concat_(result,arguments[i]);
}
return result;
}

//合并多个数组,去重,排序
var arr1 = [1,6,4,0];
var arr2 = [8,20,7,4.5];
var arr3 = [6,0,7,90,2];

var concat = function(arr1,arr2,arr3){
if(arguments.length <= 1){
return false;
}
var concat_ = function(arr1,arr2){
var arr = arr1.concat();
for(var i=0;i<arr2.length;i++){
arr.indexOf(arr2[i]) === -1 ? arr.push(arr2[i]) : 0;
}
return arr;
}
var result = concat_(arr1,arr2);
for(var i=2;i<arguments.length;i++){
result = concat_(result,arguments[i]);
}
//排序
function sortNumber(a,b){
return a - b;
}
return result.sort(sortNumber);
}