zoukankan      html  css  js  c++  java
  • 二:数组去重

    数组去重不仅在工作中经常使用,也会在面试中经常问到,现在有几种常用的方法:

    比如要将数组去重:

    const arr = [1, 2, 3, "1", 2, undefined, undefined, "undefined", NaN, NaN];

    方法一:

    直接通过indexOf 或者 includes进行判断是否存在,不存在则直接push到新数组中。

    如果数组中存在NaN的话,使用includes,因为indexOf判断不了NaN。

    let newArr1 = [];
    arr.map((item) => {
        if (newArr1.indexOf(item) === -1) {
        newArr1.push(item);
        }
    });
    console.log("newArr1===", newArr1);   // [1, 2, 3, "1", undefined, "undefined", NaN]

    方法二:

    对象的键存储数组元素的值,最终返回对象的所有键。然后使用es6的Object.keys()来获取键值。
    let temp1 = {};
    arr.map((item, i) => {
        if (temp1[item] === undefined) {
          temp1[item] = i;
        }
    });
    console.log(temp1); // {1: 0, 2: 1, 3: 2, undefined: 5, NaN: 8}
    const newArr3 = Object.keys(temp1); // [1, 2, 3, "1", undefined, "undefined", NaN]

    方法三:

    筛选中如果存在{},{a:1}此时进行去重,需要使用findIndex:查询数组是否包含某元素,如果存在返回元素的索引,否则返回-1。

    它比indexOf更加先进的地方在于能传入callback,按约定方式查询。

    const arr1 = [1, 2, 3, '1', 2, undefined, undefined,  'undefined', NaN, NaN, {}, {}, {a: 1}, {a: 1}];
    let tmp = [];
    arr1.map((item,i) => {
        if(tmp.findIndex(v => JSON.stringify(v) === JSON.stringify(item)) === -1){
            tmp.push(item);
        }
    }); 
    console.log(tmp);  // [1, 2, 3, "1", undefined, "undefined", NaN, {}, {a:1}]

    为什么要使用 JSON.stringify 来进行对比,是因为{} === {} 为false,这是因为对象堆栈的原因。

    参考:https://my.oschina.net/u/4188011/blog/4278961

  • 相关阅读:
    CentOS yum 安装svn1.8
    js 替换掉汉字 和替换非汉字 比较时间JS
    PhpStorm 10 破解
    html中link的用法
    CSS3:nth-child()伪类选择器
    提示的小三角
    css 高度自适应
    <input type="file" />浏览时只显示指定文件类型
    MySQL查询表内重复记录
    扒站小工具
  • 原文地址:https://www.cnblogs.com/liumcb/p/14786020.html
Copyright © 2011-2022 走看看