[JavaScript基础]数组去重常见的三种方式

// way one
let array = [1,2,3,4,5,4];
let array1 = [1,1,1,1,1,2,2,3];
// zepto源码实现方式,简单可比较元素
let newArray = array1.filter((element, index) => {
    return array1.indexOf(element) === index;
});

console.log(newArray);

// way two,简单可排序元素
let array2 = [1,1,1,1,1,2,2,3];
let newArray2 = array2.sort();
for(let i = 1;i < newArray2.length;i++) {
  if(newArray2[i - 1] === newArray2[i]) {
    newArray2.splice(i, 1);
    i--;
  }
}

console.log(newArray2);

// way three
// 复杂对象
// 1.简单去重 + 对象深度复制克隆
let array3 = [1,1,1,1,1,2,2,3];
let newArray3 = array3.concat();
let currentVal;
let moveVal;
for(let i = 0;i < newArray3.length;i++) {
  let currentVal = newArray3[i];
  for(let j = i + 1;j < newArray3.length;j++) {
    moveVal = newArray3[j];
    if(currentVal === moveVal) {
      newArray3.splice(j, 1);
      j--;
    }
  }
}

console.log(newArray3);

你可能感兴趣的:([JavaScript基础]数组去重常见的三种方式)