欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JavaScript常用數(shù)組去重的方法及對(duì)比詳解

 更新時(shí)間:2022年07月21日 08:44:34   作者:易函123  
數(shù)組去重在面試和工作中都是比較容易見(jiàn)到的問(wèn)題。這篇文章主要是來(lái)測(cè)試多個(gè)方法,對(duì)下面這個(gè)數(shù)組的去重結(jié)果進(jìn)行分析討論,需要的可以參考一下

前言

數(shù)組去重在面試和工作中都是比較容易見(jiàn)到的問(wèn)題。

這篇文章主要是來(lái)測(cè)試多個(gè)方法,對(duì)下面這個(gè)數(shù)組的去重結(jié)果進(jìn)行分析討論。如果有不對(duì)的地方,還請(qǐng)大家指出。

 const arr = [ 1, 1, "1", "1", 0, 0, "0", "0", true, false, "true", "false", "a", "A", undefined, undefined, "undefined", null, null, 'null', NaN, NaN, +0, -0, new String("1"), new String("1"), Symbol(1), Symbol(1), {}, {}, /a/, /a/, [], [] ];

特殊類(lèi)型

console.log(1 == "1"); // true
console.log(1 === "1"); // false

console.log(0 == "0"); // true
console.log(0 === "0"); // false

console.log(0 == +0); // true
console.log(0 === +0); // true

console.log(0 == -0); // true
console.log(0 === -0); // true

console.log(+0 == -0); // true
console.log(+0 === -0); // true

console.log(0 == false); // true
console.log(0 === false); // false

console.log(0 == undefined); // false
console.log(0 === undefined); // false

console.log(0 == null); // false
console.log(0 === null); // false

console.log(1 == true); // true
console.log(1 === true); // false

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

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

console.log(new String("1") == new String("1")); // false
console.log(new String("1") === new String("1")); // false
Object.prototype.toString.call(new String('1')) // '[object String]'


console.log(/a/ == /a/); // false
console.log(/a/ === /a/); // false
Object.prototype.toString.call(/a/); //'[object RegExp]'


console.log(Symbol(1) == Symbol(1)); // false
console.log(Symbol(1) === Symbol(1)); // false

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

console.log([] == []); // false
console.log([] === []); // false

接下來(lái),我們看看下面多個(gè)去重方法,對(duì)以上特殊類(lèi)型的去重效果。

代碼一(暴力解法)

// 暴力解法一

function unique(array) {
    if (!Array.isArray(array)) {
      console.log("type error!");
      return;
    }
    const res = [array[0]];
    let arrLen = array.length;
    let resLen = res.length;
    
    for (let i = 0; i < arrLen; i++) {
      let flag = true;
      for (let j = 0; j < resLen; j++) {
        if (array[i] === res[j]) {
          flag = false;
          break;
        }
      }
      if (flag) {
        res.push(array[i]);
        resLen = res.length;
      }
    }
    return res;
}
// [1, '1', 0, '0', true, false, 'true', 'false', 'a', 'A', undefined, 'undefined', null, 'null', NaN, NaN, String {'1'}, String {'1'}, Symbol(1), Symbol(1), {}, {}, /a/, /a/, [], []]

輸出:

[1, '1', 0, '0', true, false, 'true', 'false', 'a', 'A', undefined, 'undefined', null, 'null', NaN, NaN, String {'1'}, String {'1'}, Symbol(1), Symbol(1), {}, {}, /a/, /a/, [], []]

輸出結(jié)果說(shuō)明:

  • 去重+0、-0、0
  • NaN不去重
  • 對(duì)象new String("1")/a/、{}不去重
  • 數(shù)組[]不去重
  • Symbol(1)不去重

暴力解法,簡(jiǎn)單易理解,兼容性好。去重結(jié)果如上所示。

代碼二(ES6)

// ES6 Array.from + Set 方法一
function unique(array) {
    if (!Array.isArray(array)) {
      console.log('type error!')
      return
    }
    return Array.from(new Set(array))
}

// ES6 點(diǎn)運(yùn)算 + Set 方法二
function unique1(array) {
    if (!Array.isArray(array)) {
      console.log('type error!')
      return
    }
    return [...new Set(arr)]
}

// ES6 箭頭函數(shù) + 點(diǎn)運(yùn)算 + Set 方法三
const unique2 = (array) => {
    if (!Array.isArray(array)) {
      console.log('type error!')
      return
    }
    return [...new Set(arr)]
}

// ES6 Map + ES5 filter  方法四
function unique3(array) {
    if (!Array.isArray(array)) {
      console.log('type error!')
      return
    }
    const seen = new Map()
    return array.filter((a) => !seen.has(a) && seen.set(a, 1))
}

輸出:

[1, '1', 0, '0', true, false, 'true', 'false', 'a', 'A', undefined, 'undefined', null, 'null', NaN, String {'1'}, String {'1'}, Symbol(1), Symbol(1), {}, {}, /a/, /a/, [], []]

輸出結(jié)果說(shuō)明:

  • 去重+0-0、0
  • 去重NaN
  • 對(duì)象new String("1")/a/、{}不去重
  • 數(shù)組[]不去重
  • Symbol(1)不去重

代碼三(indexOf + forEach)

利用indexOf檢測(cè)元素在新數(shù)組是否存在

// indexOf + forEach 利用indexOf檢測(cè)元素在新數(shù)組是否存在
function unique(array) {
    if (!Array.isArray(array)) {
        console.log('type error!')
        return
    }
    const newArr = [];
    array.forEach((el) => {
      if (newArr.indexOf(el) === -1) {
        newArr.push(el);
      }
    });
    return newArr;
}

輸出:

[1, '1', 0, '0', true, false, 'true', 'false', 'a', 'A', undefined, 'undefined', null, 'null', NaN, NaN, String {'1'}, String {'1'}, Symbol(1), Symbol(1), {}, {}, /a/, /a/, [], []]

輸出結(jié)果說(shuō)明:

  • 去重+0、-0、0
  • NaN不去重
  • 對(duì)象new String("1")/a/、{}不去重
  • 數(shù)組[]不去重
  • Symbol(1)不去重

代碼四(indexOf + filter)

利用indexOf檢測(cè)元素在數(shù)組中第一次出現(xiàn)的位置是否和元素現(xiàn)在的位置相等

// indexOf + forEach 利用indexOf檢測(cè)元素在新數(shù)組是否存在
function unique(array) {
    if (!Array.isArray(array)) {
        console.log('type error!')
        return
    }
    return array.filter((item, index) => {
        return array.indexOf(item) === index;
    });
}

console.log([NaN].indexOf(NaN)); // -1

輸出:

[1, '1', 0, '0', true, false, 'true', 'false', 'a', 'A', undefined, 'undefined', null, 'null', String {'1'}, String {'1'}, Symbol(1), Symbol(1), {}, {}, /a/, /a/, [], []]

輸出結(jié)果說(shuō)明:

  • 去重+0-0、0
  • 兩個(gè)NaN都會(huì)被刪除
  • 對(duì)象new String("1")、/a/、{}不去重
  • 數(shù)組[]不去重
  • Symbol(1)不去重

重點(diǎn):

console.log([NaN].indexOf(NaN)); // -1

代碼五(sort排序,不支持Symbol)

sort()方法主要是用于對(duì)數(shù)組進(jìn)行排序,默認(rèn)情況下該方法是將數(shù)組元素轉(zhuǎn)換成字符串,然后按照ASC碼進(jìn)行排序

// sort()方法不支持Symbol,Symbol不支持轉(zhuǎn)換成字符串
function unique(array) {
    if (!Array.isArray(array)) {
      console.log("type error!");
      return;
    }
    const sortArr = array.sort();
    const newArr = [];
    sortArr.forEach((el, i) => {
      if (sortArr[i] !== sortArr[i - 1]) {
        newArr.push(el);
      }
    });
    return newArr;
}

輸出:

[[], [], /a/, /a/, 0, "0", 0, 1, "1", String {'1'}, String {'1'}, "A", NaN, NaN, {}, {}, "a", false, "false", null, "null", true, "true", "undefined", undefined]

輸出結(jié)果說(shuō)明:

  • +0、-00、"0"位置不同會(huì)導(dǎo)致去重不了
  • NaN不去重
  • 對(duì)象new String("1")、/a/{}不去重
  • 數(shù)組[]不去重
  • sort()方法不支持處理含有Symbol的數(shù)組

代碼六(includes)

利用includes()方法檢查新數(shù)組是否包含原數(shù)組的每一項(xiàng)

// 利用includes()方法檢查新數(shù)組是否包含原數(shù)組的每一項(xiàng)
function unique(array) {
    if (!Array.isArray(array)) {
      console.log("type error!");
      return;
    }
    
    const newArr = [];
    array.forEach((el) => {
      newArr.includes(el) ? newArr : newArr.push(el);
    });
    return newArr;
}

輸出:

[1, '1', 0, '0', true, false, 'true', 'false', 'a', 'A', undefined, 'undefined', null, 'null', NaN, String {'1'}, String {'1'}, Symbol(1), Symbol(1), {}, {}, /a/, /a/, [], []]

輸出結(jié)果說(shuō)明:

  • 去重+0、-0、0
  • 去重NaN
  • 對(duì)象new String("1")、/a/{}不去重
  • 數(shù)組[]不去重
  • Symbol不去重

代碼七(includes+reduce)

利用includes()方法檢查新數(shù)組是否包含原數(shù)組的每一項(xiàng)

// 利用includes()方法檢查新數(shù)組是否包含原數(shù)組的每一項(xiàng)
function unique(array) {
    if (!Array.isArray(array)) {
      console.log("type error!");
      return;
    }
    
    return array.reduce((pre, cur) => {
      !pre.includes(cur) && pre.push(cur);
      return pre;
    }, []);
}

輸出:

[1, '1', 0, '0', true, false, 'true', 'false', 'a', 'A', undefined, 'undefined', null, 'null', NaN, String {'1'}, String {'1'}, Symbol(1), Symbol(1), {}, {}, /a/, /a/, [], []]

輸出結(jié)果說(shuō)明:

  • 去重+0、-00
  • 去重NaN
  • 對(duì)象new String("1")、/a/、{}不去重
  • 數(shù)組[]不去重
  • Symbol不去重

代碼八(對(duì)象key)

利用了對(duì)象的key不可以重復(fù)的特性來(lái)進(jìn)行去重

// 利用了對(duì)象的key不可以重復(fù)的特性來(lái)進(jìn)行去重
function unique(array) {
    if (!Array.isArray(array)) {
      console.log("type error!");
      return;
    }
    
    const obj = {};
    const newArr = [];
    array.forEach((val) => {
      if (!obj[typeof val + JSON.stringify(val)]) {
        // 將對(duì)象序列化之后作為key來(lái)使用
        obj[typeof val + JSON.stringify(val)] = 1;
        newArr.push(val);
      }
    });
    return newArr;
}

輸出:

[1, '1', 0, '0', true, false, 'true', 'false', 'a', 'A', undefined, 'undefined', null, 'null', NaN, String {'1'}, Symbol(1), {}, []]

輸出結(jié)果說(shuō)明:

  • 去重+0、-0、0
  • 去重NaN
  • 去重對(duì)象new String("1")、{};兩個(gè)/a/全部被刪除了
  • 去重?cái)?shù)組[]
  • 去重Symbol

將不該去重的Symbol去重了;將兩個(gè)/a/全部刪除了

總結(jié)

方法結(jié)果說(shuō)明
for循環(huán)暴力解法[1, '1', 0, '0', true, false, 'true', 'false', 'a', 'A', undefined, 'undefined', null, 'null', NaN, NaN, String {'1'}, String {'1'}, Symbol(1), Symbol(1), {}, {}, /a/, /a/, [], []]1.去重+0、-0、0;
2.NaN不去重;
3.對(duì)象new String("1")、/a/、{}不去重;
4.數(shù)組[]不去重;
5.Symbol(1)不去重;
ES6解法[1, '1', 0, '0', true, false, 'true', 'false', 'a', 'A', undefined, 'undefined', null, 'null', NaN, String {'1'}, String {'1'}, Symbol(1), Symbol(1), {}, {}, /a/, /a/, [], []1.去重+0、-0、0;
2.去重NaN;
3.對(duì)象new String("1")、/a/、{}不去重;
4.數(shù)組[]不去重;
5.Symbol(1)不去重;
indexOf + forEach[1, '1', 0, '0', true, false, 'true', 'false', 'a', 'A', undefined, 'undefined', null, 'null', NaN, NaN, String {'1'}, String {'1'}, Symbol(1), Symbol(1), {}, {}, /a/, /a/, [], []]1.去重+0、-0、0;
2.NaN不去重;
3.對(duì)象new String("1")、/a/、{}不去重;
4.數(shù)組[]不去重;
5.Symbol(1)不去重;
indexOf + filter[1, '1', 0, '0', true, false, 'true', 'false', 'a', 'A', undefined, 'undefined', null, 'null', String {'1'}, String {'1'}, Symbol(1), Symbol(1), {}, {}, /a/, /a/, [], []]1.去重+0、-0、0;
2.兩個(gè)NaN都會(huì)被刪除;
3.對(duì)象new String("1")、/a/、{}不去重;
4.數(shù)組[]不去重;
5.Symbol(1)不去重;
sort排序,不支持Symbol[[], [], /a/, /a/, 0, "0", 0, 1, "1", String {'1'}, String {'1'}, "A", NaN, NaN, {}, {}, "a", false, "false", null, "null", true, "true", "undefined", undefined]1.+0、-0、0、"0"位置不同會(huì)導(dǎo)致去重不了
2.NaN不去重;
3.對(duì)象new String("1")、/a/、{}不去重;
4.數(shù)組[]不去重;
5.sort()方法不支持處理含有Symbol的數(shù)組;
includes[1, '1', 0, '0', true, false, 'true', 'false', 'a', 'A', undefined, 'undefined', null, 'null', NaN, String {'1'}, String {'1'}, Symbol(1), Symbol(1), {}, {}, /a/, /a/, [], []]1.去重+0、-0、0;
2.去重NaN;
3.對(duì)象new String("1")、/a/、{}不去重;
4.數(shù)組[]不去重;
5.Symbol(1)不去重;
includes+reduce[1, '1', 0, '0', true, false, 'true', 'false', 'a', 'A', undefined, 'undefined', null, 'null', NaN, String {'1'}, String {'1'}, Symbol(1), Symbol(1), {}, {}, /a/, /a/, [], []]1.去重+0、-0、0;
2.去重NaN;
3.對(duì)象new String("1")、/a/、{}不去重;
4.數(shù)組[]不去重;
5.Symbol(1)不去重;
對(duì)象key[1, '1', 0, '0', true, false, 'true', 'false', 'a', 'A', undefined, 'undefined', null, 'null', NaN, String {'1'}, Symbol(1), {}, []]1.去重+0、-0、0;
2.去重NaN;
3.去重對(duì)象new String("1")、{};兩個(gè)/a/全部被刪除了;
4.去重?cái)?shù)組[];5.去重Symbol

上面只是簡(jiǎn)單結(jié)果的去重總結(jié),具體的去重選擇還需要根據(jù)我們業(yè)務(wù)場(chǎng)景來(lái)選擇去重方法。

演示地址

可以去Github倉(cāng)庫(kù)查看演示代碼

到此這篇關(guān)于JavaScript常用數(shù)組去重的方法及對(duì)比詳解的文章就介紹到這了,更多相關(guān)JavaScript數(shù)組去重內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Bootstrap基本組件學(xué)習(xí)筆記之進(jìn)度條(15)

    Bootstrap基本組件學(xué)習(xí)筆記之進(jìn)度條(15)

    這篇文章主要為大家詳細(xì)介紹了Bootstrap基本組件學(xué)習(xí)筆記之進(jìn)度條,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-12-12
  • js自動(dòng)生成的元素與頁(yè)面原有元素發(fā)生堆疊的解決方法

    js自動(dòng)生成的元素與頁(yè)面原有元素發(fā)生堆疊的解決方法

    js自動(dòng)生成的元素與頁(yè)面原有元素發(fā)生堆疊通過(guò)去除浮動(dòng),給原有元素(商品擴(kuò)展信息部分)加上clear:both; 果然正常了
    2013-10-10
  • 跟我學(xué)Nodejs(三)--- Node.js模塊

    跟我學(xué)Nodejs(三)--- Node.js模塊

    這是本系列的第三篇文章了,前面2篇網(wǎng)友們反饋回來(lái)不少的消息,加上最近2天比較忙,一直沒(méi)來(lái)得及整理,周末了,趕緊給大家整理下發(fā)出來(lái),本文講的是node.js模塊
    2014-05-05
  • ES6記錄異步函數(shù)的執(zhí)行時(shí)間詳解

    ES6記錄異步函數(shù)的執(zhí)行時(shí)間詳解

    在這篇文章里,我會(huì)實(shí)現(xiàn)一個(gè)可重用的函數(shù)來(lái)處理 JavaScript 延時(shí)異步操作。有需要的小伙伴們可以參考借鑒,下面來(lái)一起看看。
    2016-08-08
  • eval的兩組性能測(cè)試數(shù)據(jù)

    eval的兩組性能測(cè)試數(shù)據(jù)

    最近對(duì)eval火爆的討論,教主 @Franky 和 灰大 @otakustay 也給了精彩的數(shù)據(jù)分析,剛好之前也做過(guò)類(lèi)似的測(cè)試,我也跟風(fēng)湊個(gè)熱鬧,提供兩組數(shù)據(jù)供大家參考
    2012-08-08
  • JS刪除數(shù)組中某個(gè)元素的四種方式總結(jié)

    JS刪除數(shù)組中某個(gè)元素的四種方式總結(jié)

    js刪除指定元素方法有很多,下面這篇文章主要給大家介紹了關(guān)于JS刪除數(shù)組中某個(gè)元素的四種方式,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-02-02
  • 基于JavaScript 性能優(yōu)化技巧心得(分享)

    基于JavaScript 性能優(yōu)化技巧心得(分享)

    下面小編就為大家分享一篇基于JavaScript 性能優(yōu)化技巧心得,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2017-12-12
  • 控制臺(tái)報(bào)錯(cuò):Cannot?access?'xxx'?before?initialization解決方法

    控制臺(tái)報(bào)錯(cuò):Cannot?access?'xxx'?before?initializatio

    這篇文章主要給大家介紹了關(guān)于控制臺(tái)報(bào)錯(cuò):Cannot?access?'xxx'?before?initialization的解決方法,文中通過(guò)代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-11-11
  • js獲取Element元素的四種常用方法

    js獲取Element元素的四種常用方法

    本文主要介紹了js獲取Element元素的四種常用方法,通過(guò)介紹getElementById、getElementsByClassName、getElementsByTagName和querySelector等方法,幫助讀者了解如何通過(guò)不同的方式獲取頁(yè)面中的元素,感興趣的可以了解一下
    2023-08-08
  • JS合并兩個(gè)數(shù)組的方法詳解

    JS合并兩個(gè)數(shù)組的方法詳解

    這篇文章主要詳細(xì)介紹了JS合并兩個(gè)數(shù)組的方法,文中有詳細(xì)的代碼示例,對(duì)我們學(xué)習(xí)JS有一定的幫助,感興趣的同學(xué)可以參考一下
    2023-06-06

最新評(píng)論