当前位置: 移动技术网 > IT编程>开发语言>JavaScript > js数组去重(最优方法)笔记

js数组去重(最优方法)笔记

2020年03月11日  | 移动技术网IT编程  | 我要评论

资料:

remove duplicate values from js array [duplicate]

大致思路

遍历数组的各个项并判断某项是否重复。时间复杂度往往是 o(n^2)

优化:通过object,或者set,借助散列表查找的优秀性能来降低复杂度

下面记录几种方法

去重的是单一基础类型(number)可以用 遍历 + obj-keys

如果有多类型的话,可能会出现
1 和 字符串'1' 被认为是重复的问题

function merge2array5(origin) {
  const result = [];
  const tagobj = {};
  for (const i of origin) {
    if (!tagobj[i]) {
      result.push(i);
      tagobj[i] = 1;
    }
  }
  return result;
}

去重的是多种基础类型

用 for + set

function merge2array6(origin) {
  const result = [];
  const set = new set();
  for (const i of origin) {
    if (!set.has(i)) {
      result.push(i);
      set.add(i);
    }
  }
  return result;
}

代码量少的写法

// 方法1
function merge2array4 (origin, target) {
  return array.from(new set([...origin, ...target]))
}


//方法2

function onlyunique(value, index, self) { 
    return self.indexof(value) === index;
}
// usage example:
var a = ['a', 1, 'a', 2, '1'];
var unique = a.filter( onlyunique ); // returns ['a', 1, 2, '1']

最后

stack overflow的回答上有句话:

however, if you need an array with unique elements, why not use sets right from the beginning?

hhhhhhh :d

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网