JS实现数组去重

/ Javascript前端 / 没有评论 / 477浏览

题目:用至少两种方法来实现,编写一个数组去重函数,如输入数组[1,"a",{b:2},{c:3},{c:"3"},"1","a"],返回[1,"a",{b: 2},{c: 3},{c:"3"}, "1"]

const arr = [1,"a",{b:2},{c:3},{c:"3"},"1","a"];

方法一:ES6的Set对象

[...new Set(arr)];

方法二:数组的filter()方法和indexOf()方法

arr.filter((item, key, array) => array.indexOf(item) === key);

方法三:利用下标查询

function unique(arr) {
  const newArr = [arr[0]];
  for (let i = 1; i < arr.length; i++) {
    if (newArr.indexOf(arr[i]) === -1) {
      newArr.push(arr[i]);
    }
  }
  return newArr;
}

方法四:先将原数组排序,再与相邻的进行比较,如果不同则存入新数组。

function unique(arr) {
  const arr2 = arr.sort();
  const newArr = [arr2[0]];
  for (let i = 1; i < arr2.length; i++) {
    if (arr[i] !== newArr[newArr.length - 1]) {
      newArr.push(arr[i]);
    }
  }
  return newArr;
}