JavaScript

JS 中常用的数组去重方法

2020-10-19  本文已影响0人  limengzhe

Set

Set 是 ES2015 新增的一种数据结构,类似数组,Set 中的元素只会出现一次,即 Set 中的元素是唯一的。

const a = [1, 2, 3, 4, 5, 5, 5];
const b = Array.from(new Set(a));

console.log(b); // expected output: [ 1, 2, 3, 4, 5 ]

双层 for 循环

判断每一项是否相等

function unique(arr) {
  for (let i = 0; i < arr.length; i++) {
    for (let j = i + 1; j < arr.length; j++) {
      if (arr[i] == arr[j]) {
        arr.splice(j, 1);
        j--;
      }
    }
  }
  return arr;
}

const a = [1, 2, 3, 4, 5, 5, 5];
const b = unique(a);

console.log(b); // expected output: [ 1, 2, 3, 4, 5 ]

indexOf()includes()

创建一个新数组,利用 indexOf()includes() 判断新数组是否包含已存在的元素,如果没有则添加到新数组。

function unique(source) {
  let target = [];
  source.forEach(item => {
    if (target.indexOf(item) < 0) {
      target.push(item);
    }
  });
  return target;
}

const a = [1, 2, 3, 4, 5, 5, 5];
const b = unique(a);

console.log(b); // expected output: [ 1, 2, 3, 4, 5 ]

filter

利用 filter 返回元素在数组中首次出现的索引值和该元素的索引一样的元素的新数组,即重复出现的元素会被过滤掉。

function unique(arr) {
  return arr.filter((item, index, arr) => arr.indexOf(item, 0) === index);
}

const a = [1, 2, 3, 4, 5, 5, 5];
const b = unique(a);

console.log(b);
上一篇 下一篇

猜你喜欢

热点阅读