remove duplicate values from js array [duplicate]
遍历数组的各个项并判断某项是否重复。时间复杂度往往是 o(n^2)
优化:通过object,或者set,借助散列表查找的优秀性能来降低复杂度
如果有多类型的话,可能会出现
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
如对本文有疑问, 点击进行留言回复!!
同事牛逼啊,写了个隐藏 bug,我排查了 3 天才解决问题!
【JavaScript笔记(一)】万丈高楼平地起 - 基本概念篇
轻松解决 org.apache.taglibs.standard.tlv.JstlCoreTLV 困惑
网友评论