Remove duplicate values from JS array [duplicate]性能
遍歷數組的各個項並判斷某項是否重複。時間複雜度每每是 O(n^2)優化
優化:經過object,或者set,藉助散列表查找的優秀性能來下降複雜度code
若是有多類型的話,可能會出現
1 和 字符串'1' 被認爲是重複的問題ip
function merge2Array5(origin) { const result = []; const tagObj = {}; for (const i of origin) { if (!tagObj[i]) { result.push(i); tagObj[i] = 1; } } return result; }
用 for + setelement
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的回答上有句話:rem
However, if you need an array with unique elements, why not use sets right from the beginning?字符串
hhhhhhh :Dget