數組去重

數組去重是一個經常會用到的方法,我寫了一個測試模板,測試一下常見的數據去重的方法的性能

測試模板

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: '數學'}
]
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 數組去重 是常見的面試考點,所以我就試著深入學習一下。網上也有很多數組去重的文章,但我自己覺得分析地不夠深入,其實...
    前端西瓜哥閱讀 703評論 0 1
  • 2019.08.02補:對象數組建議直接循環(huán)然后使用工具庫(lodash)的深比較,評論里也有指出,文章的方法有些...
    始悔不悟閱讀 61,310評論 13 26
  • 1. 冒泡排序 //外層循環(huán)代表趟數 每趟確定一個最(大)值 故應有arr.length-1 趟 var a...
    蜉蝣_fe74閱讀 399評論 0 0
  • 一般操作 最簡單的方式,優(yōu)點兼容性好,缺點是需要兩次 for 循環(huán),性能較差 數組的 indexOf 屬性 ES5...
    啊燦2580閱讀 307評論 0 0
  • 游戲如人生,人生如游戲,確實如此。 許多游戲里,角色有自己的能量條,消耗殆盡,就此over。生活里,每個人也都有自...
    微酸小小魚閱讀 439評論 0 1

友情鏈接更多精彩內容