一,两个数组的合并去重:
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; } console.log(concat_(arr1,arr2)); //['a','b','c','d']
二,多个数组的合并去重:
var arr1 = ['a','b']; var arr2 = ['a','c','d']; var arr3 = [1,'d',undefined,true,null]; //合并多个数组,去重 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; } console.log(concat_(arr1,arr2,arr3));//["a", "b", "c", "d", 1, undefined, true, null]
三,多个数组合并,去重,排序:
//合并多个数组,去重,排序 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); } console.log(concat_(arr1,arr2,arr3))//[0, 1, 2, 4, 4.5, 6, 7, 8, 20, 90]
参考:
http://m.blog.csdn.net/article/details?id=49634041