數組去重是一個經常會用到的方法,我寫了一個測試模板,測試一下常見的數據去重的方法的性能
測試模板
let arr1 = Array.from(new Array(100000), (x, index)=>{
return index
})
let arr2 = Array.from(new Array(50000), (x, index)=>{
return index+index
})
let start = new Date().getTime()
console.log('開始數組去重')
function distinct(a, b) {
// 數組去重
}
console.log('去重后的長度', distinct(arr1, arr2).length)
let end = new Date().getTime()
console.log('耗時', end - start)
1、Array.filter() + indexOf
方法思路:將兩個數組拼接為一個數組,然后使用 ES6 中的 Array.filter() 遍歷數組,并結合 indexOf 來排除重復項
function distinct(a, b) {
let arr = a.concat(b);
return arr.filter((item, index)=> {
return arr.indexOf(item) === index
})
}

1.png
2、雙重 for 循環(huán)
方法思路:外層循環(huán)遍歷元素,內層循環(huán)檢查是否重復,當有重復值的時候,可以使用 push(),也可以使用 splice()
function distinct(a, b) {
let arr = a.concat(b);
for (let i=0, len=arr.length; i<len; i++) {
for (let j=i+1; j<len; j++) {
if (arr[i] == arr[j]) {
arr.splice(j, 1);
// splice 會改變數組長度,所以要將數組長度 len 和下標 j 減一
len--;
j--;
}
}
}
return arr
}

2.png
3、for...of + includes()
方法思路:雙重for循環(huán)的升級版,外層用 for...of 語句替換 for 循環(huán),把內層循環(huán)改為 includes()。先創(chuàng)建一個空數組,當 includes() 返回 false 的時候,就將該元素 push 到空數組中 。類似的,還可以用 indexOf() 來替代 includes()
function distinct(a, b) {
let arr = a.concat(b)
let result = []
for (let i of arr) {
!result.includes(i) && result.push(i)
}
return result
}

3.png
4、Array.sort()
方法思路:首先使用 sort() 將數組進行排序,然后比較相鄰元素是否相等,從而排除重復項
function distinct(a, b) {
let arr = a.concat(b)
arr = arr.sort()
let result = [arr[0]]
for (let i=1, len=arr.length; i<len; i++) {
arr[i] !== arr[i-1] && result.push(arr[i])
}
return result
}

4.png
5、new Set()
ES6 新增了 Set 這一數據結構,類似于數組,但Set 的成員具有唯一性
function distinct(a, b) {
return Array.from(new Set([...a, ...b]))
}

5.png
6、for...of + Object
方法思路:首先創(chuàng)建一個空對象,然后用 for 循環(huán)遍歷,利用對象的屬性不會重復這一特性,校驗數組元素是否重復
function distinct(a, b) {
let arr = a.concat(b)
let result = []
let obj = {}
for (let i of arr) {
if (!obj[i]) {
result.push(i)
obj[i] = 1
}
}
return result
}

6.png
測試結果一目了然,幾種方法的性能 6>5>4>3>1>2
數組對象去重
let arrObj = [
{ id: 1, book: '語文' },
{ id: 1, book: '語文' },
{ id: 4, book: '數學' },
{ id: 3, book: '英語' },
{ id: 1, book: '語文' },
{ id: 4, book: '語文' }
];
let map = new Map();
for (let item of arrObj) {
if (!map.has(item.id)) {
map.set(item.id, item);
};
};
arr = [...map.values()];
console.log(arr);
去重結果
[
{id: 1, book: '語文'}
{ id: 3, book: '英語'}
{ id: 4, book: '數學'}
]