數組去重

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
    })
}//性能不高

2、雙重 for 循環
最容易理解的方法,外層循環遍歷元素,內層循環檢查是否重複,當有重複值的時候,可使用 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
}//性能有點差

3、for...of + includes()

雙重for循環的升級版,外層用 for...of 語句替換 for 循環,把內層循環改成 includes(),
先建立一個空數組,當 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
}//性能不高

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
}//性能良好

5、new Set()
ES6 新增了 Set 這一數據結構,相似於數組,但 Set 的成員具備惟一性
基於這一特性,就很是適合用來作數組去重了
function distinct(a, b) {
    return Array.from(new Set([...a, ...b]))
}//性能優秀

6、for...of + Object
這個方法我只在一些文章裏見過,實際工做中倒沒怎麼用,
首先建立一個空對象,而後用 for 循環遍歷,
利用對象的屬性不會重複這一特性,校驗數組元素是否重複
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
}//性能很是優秀,但彷佛有缺陷,仍是用上面的吧
相關文章
相關標籤/搜索