1. 程式人生 > >陣列去重(es5,es6)

陣列去重(es5,es6)

const arr = [1,2,"1",null,null,undefined,undefined,false,false,NaN,NaN];

1.0 遍歷 無法判斷NaN
//for迴圈去重,效率較高
const unique1 = (arr)=>{
  const newArr = [];
  let item;
  for (let i = 0 , len = arr.length ; i < len; i++) {
    item = arr[i];
    if(newArr.indexOf(item) === -1){
      newArr.push(item);
    }
  }
  return newArr;
}
console.log('遍歷:unique1',unique1(arr));//[1, 2, null, false, NaN, NaN]

//forEach  效率不如for,判斷不出NaN
const unique2 = (arr)=>{
  const newArr = [];
  arr.forEach(item=>{
    if(newArr.indexOf(item) === -1){
      newArr.push(item);
    }
  })
  return newArr;
}
console.log('遍歷:unique2',unique2(arr));//[1, 2, null, false, NaN, NaN]

//reduce
const unique3 = (arr)=>{
  return arr.reduce((pre,next)=>{
    if(pre.indexOf(next) === -1){
      pre.push(next)
    };
    return pre;
  },[])
}
console.log('遍歷:unique3',unique3(arr));// [1, 2, null, false, NaN, NaN]
//解決NaN無法排除問題
const unique1_1 = (arr)=>{
  const newArr = [];
  let item;
  let flag = true;
  for (let i = 0 , len = arr.length ; i < len; i++) {
    item = arr[i];
    if(newArr.indexOf(item) === -1){
      if(item != item){ //排除NaN
        if(flag){
          newArr.push(item);
          flag = false;
        }
      }else {
        newArr.push(item);
      }
    }
  }
  return newArr;
}

console.log('解決NaN問題:unique1_1',unique1_1(arr));//[1, 2, null, false, NaN]
2.0 索引去重 把NaN直接全部去除掉了
//2.1for
 const unique4 = (arr)=>{
   const newArr = [];
   let item;
   for (let i = 0 , len = arr.length; i < len; i++) {
     item = arr[i];
     if(arr.indexOf(item) === i){
       newArr.push(item);
     }
   }
   return newArr;
 }
 console.log('索引去重:unique4',unique4(arr));//[1, 2, null, false]


//2.2filter
const unique5 = (arr)=>{
  return arr.filter((item,index,arr)=>arr.indexOf(item) === index)
}
console.log('索引去重:unique4',unique5(arr));//[1, 2, null, false]
3.0集合轉換 效率低,能去掉重複NaN;
//Set
const unique6 = (arr)=>{
  return Array.from(new Set(arr));
}
console.log('集合轉換:unique6',unique6(arr));



掛載方法到Array上
const unique = function(){
  return Array.from(new Set(this));
}
Array.prototype.unique = unique;
const uniqueArr = arr.unique();

總結: 遍歷無法判斷NaN需要手動判斷,for效率最高;索引去重直接把所有NaN幹掉了,看情況使用;Set去重簡單、能去掉NaN,但是效率最低;