javascript數組去重

JavaScript數組去重

雙層循環

使用雙層嵌套循環是最原始的方法:數組

var array = ['a','b','a'];

function unique(array) {
    // res用來存儲結果
    var res = [];
    for (var i = 0, arrayLen = array.length; i < arrayLen; i++) {
        for (var j = 0, resLen = res.length; j < resLen; j++ ) {
            if (array[i] === res[j]) {
                break;
            }
        }
        // 若是array[i]是惟一的,那麼執行完循環,j等於resLen
        if (j === resLen) {
            res.push(array[i])
        }
    }
    return res;
}

console.log(unique(array)); // ['a','b']

外層循環 array 內層循環 res, 當 array[i]res[j] 相等時,跳出循環。不然說明元素惟一,這時 j === resLen 成立,將此元素添加到 res 中。數據結構

indexOf

使用 indexOf 能夠返回某個元素在數組中的索引,不存在則返回 -1,能夠用來判斷某個值在數組中是否存在。優化

var array = ['a','b','a'];

function unique(array) {
    var res = [];
    for (var i = 0, len = array.length; i < len; i++) {
        var current = array[i];
        if (res.indexOf(current) === -1) {
            res.push(current)
        }
    }
    return res;
}

console.log(unique(array));

排序後去重

試想咱們先將要去重的數組使用 sort 方法排序後,相同的值就會被排在一塊兒,而後咱們就能夠只判斷當前元素與上一個元素是否相同,相同就說明重複,不相同就添加進 res,讓咱們寫個 demo:code

var array = [1, 1, '1'];

function unique(array) {
    var res = [];
    var sortedArray = array.concat().sort();
    var seen;
    for (var i = 0, len = sortedArray.length; i < len; i++) {
        // 若是是第一個元素或者相鄰的元素不相同
        if (!i || seen !== sortedArray[i]) {
            res.push(sortedArray[i])
        }
        seen = sortedArray[i];
    }
    return res;
}

console.log(unique(array));

若是咱們對一個已經排好序的數組去重,這種方法效率確定高於使用 indexOf。對象

filter

ES5 提供了 filter 方法,咱們能夠用來簡化外層循環:排序

好比使用 indexOf 的方法:索引

var array = [1, 2, 1, 1, '1'];

function unique(array) {
    var res = array.filter(function(item, index, array){
        return array.indexOf(item) === index;
    })
    return res;
}

console.log(unique(array));

排序去重的方法:ip

var array = [1, 2, 1, 1, '1'];

function unique(array) {
    return array.concat().sort().filter(function(item, index, array){
        return !index || item !== array[index - 1]
    })
}

console.log(unique(array));

Object 鍵值對

這種方法是利用一個空的 Object 對象,咱們把數組的值存成 Object 的 key 值,好比 Object[value1] = true,在判斷另外一個值的時候,若是 Object[value2]存在的話,就說明該值是重複的。示例代碼以下:字符串

var array = [1, 2, 1, 1, '1'];

function unique(array) {
    var obj = {};
    return array.filter(function(item, index, array){
        return obj.hasOwnProperty(item) ? false : (obj[item] = true)
    })
}

console.log(unique(array)); // [1, 2]

咱們能夠發現,是有問題的,由於 1 和 '1' 是不一樣的,可是這種方法會判斷爲同一個值,這是由於對象的鍵值只能是字符串,因此咱們可使用 typeof item + item 拼成字符串做爲 key 值來避免這個問題:string

var array = [1, 2, 1, 1, '1'];

function unique(array) {
    var obj = {};
    return array.filter(function(item, index, array){
        return obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item] = true)
    })
}

console.log(unique(array)); // [1, 2, "1"]

然而,即使如此,咱們依然沒法正確區分出兩個對象,好比 {value: 1} 和 {value: 2},由於 typeof item + item 的結果都會是 object[object Object],不過咱們可使用 JSON.stringify 將對象序列化:

var array = [{value: 1}, {value: 1}, {value: 2}];

function unique(array) {
    var obj = {};
    return array.filter(function(item, index, array){
        console.log(typeof item + JSON.stringify(item))
        return obj.hasOwnProperty(typeof item + JSON.stringify(item)) ? false : (obj[typeof item + JSON.stringify(item)] = true)
    })
}

console.log(unique(array)); // [{value: 1}, {value: 2}]

ES6

隨着 ES6 的到來,去重的方法又有了進展,好比咱們可使用 Set 和 Map 數據結構,以 Set 爲例,ES6 提供了新的數據結構 Set。它相似於數組,可是成員的值都是惟一的,沒有重複的值。

是否是感受就像是爲去重而準備的?讓咱們來寫一版:

var array = [1, 2, 1, 1, '1'];

function unique(array) {
   return Array.from(new Set(array));
}

console.log(unique(array)); // [1, 2, "1"]

甚至能夠再簡化下:

function unique(array) {
    return [...new Set(array)];
}

還能夠再簡化下:

var unique = (a) => [...new Set(a)]

此外,若是用 Map 的話:

function unique (arr) {
    const seen = new Map()
    return arr.filter((a) => !seen.has(a) && seen.set(a, 1))
}

特殊類型比較

去重的方法就到此結束了,然而要去重的元素類型多是多種多樣,除了例子中簡單的 1 和 '1' 以外,其實還有 null、undefined、NaN、對象等,那麼對於這些元素,以前的這些方法的去重結果又是怎樣呢?

在此以前,先讓咱們先看幾個例子:

var str1 = '1';
var str2 = new String('1');

console.log(str1 == str2); // true
console.log(str1 === str2); // false

console.log(null == null); // true
console.log(null === null); // true

console.log(undefined == undefined); // true
console.log(undefined === undefined); // true

console.log(NaN == NaN); // false
console.log(NaN === NaN); // false

console.log(/a/ == /a/); // false
console.log(/a/ === /a/); // false

console.log({} == {}); // false
console.log({} === {}); // false

那麼,對於這樣一個數組

var array = [1, 1, '1', '1', null, null, undefined, undefined, new String('1'), new String('1'), /a/, /a/, NaN, NaN];

以上各類方法去重的結果究竟是什麼樣的呢?

我特意整理了一個列表,咱們重點關注下對象和 NaN 的去重狀況:

方法 結果 說明
for循環 [1, "1", null, undefined, String, String, /a/, /a/, NaN, NaN] 對象和 NaN 不去重
indexOf [1, "1", null, undefined, String, String, /a/, /a/, NaN, NaN] 對象和 NaN 不去重
sort [/a/, /a/, "1", 1, String, 1, String, NaN, NaN, null, undefined] 對象和 NaN 不去重 數字 1 也不去重
filter + indexOf [1, "1", null, undefined, String, String, /a/, /a/] 對象不去重 NaN 會被忽略掉
filter + sort [/a/, /a/, "1", 1, String, 1, String, NaN, NaN, null, undefined] 對象和 NaN 不去重 數字 1 不去重
優化後的鍵值對方法 [1, "1", null, undefined, String, /a/, NaN] 所有去重
Set [1, "1", null, undefined, String, String, /a/, /a/, NaN] 對象不去重 NaN 去重

想了解爲何會出現以上的結果,看兩個 demo 便能明白:

// demo1
var arr = [1, 2, NaN];
arr.indexOf(NaN); // -1

indexOf 底層仍是使用 === 進行判斷,由於 NaN ==== NaN 的結果爲 false,因此使用 indexOf 查找不到 NaN 元素

// demo2
function unique(array) {
   return Array.from(new Set(array));
}
console.log(unique([NaN, NaN])) // [NaN]

Set 認爲儘管 NaN === NaN 爲 false,可是這兩個元素是重複的。

相關文章
相關標籤/搜索