【跟着大佬学JavaScript】之数组去重(结果对比)

前言

数组去重在面试和工作中都是比较容易见到的问题。

这篇文章主要是来测试多个方法,对下面这个数组的去重结果进行分析讨论。如果有不对的地方,还请大家指出。

 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/, [], [] ];

特殊类型

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

接下来,我们看看下面多个去重方法,对以上特殊类型的去重效果。

代码一(暴力解法)

// 暴力解法一

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/, [], []]

输出结果说明:

  1. 去重+0-00
  2. NaN不去重
  3. 对象new String("1")/a/{}不去重
  4. 数组[]不去重
  5. Symbol(1)不去重

暴力解法,简单易理解,兼容性好。去重结果如上所示。

代码二(ES6)

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

// ES6 点运算 + Set 方法二
function unique1(array) {
    if (!Array.isArray(array)) {
      console.log('type error!')
      return
    }
    return [...new Set(arr)]
}

// ES6 箭头函数 + 点运算 + 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/, [], []]

输出结果说明:

  1. 去重+0-00
  2. 去重NaN
  3. 对象new String("1")/a/{}不去重
  4. 数组[]不去重
  5. Symbol(1)不去重

代码三(indexOf + forEach)

利用indexOf检测元素在新数组是否存在

// indexOf + forEach 利用indexOf检测元素在新数组是否存在
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/, [], []]

输出结果说明:

  1. 去重+0-00
  2. NaN不去重
  3. 对象new String("1")/a/{}不去重
  4. 数组[]不去重
  5. Symbol(1)不去重

代码四(indexOf + filter)

利用indexOf检测元素在数组中第一次出现的位置是否和元素现在的位置相等

// indexOf + forEach 利用indexOf检测元素在新数组是否存在
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/, [], []]

输出结果说明:

  1. 去重+0-00
  2. 两个NaN都会被删除
  3. 对象new String("1")/a/{}不去重
  4. 数组[]不去重
  5. Symbol(1)不去重

重点:

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

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

sort()方法主要是用于对数组进行排序,默认情况下该方法是将数组元素转换成字符串,然后按照ASC码进行排序

// sort()方法不支持Symbol,Symbol不支持转换成字符串
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]

输出结果说明:

  1. +0-00"0"位置不同会导致去重不了
  2. NaN不去重
  3. 对象new String("1")/a/{}不去重
  4. 数组[]不去重
  5. sort()方法不支持处理含有Symbol的数组

代码六(includes)

利用includes()方法检查新数组是否包含原数组的每一项

// 利用includes()方法检查新数组是否包含原数组的每一项
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/, [], []]

输出结果说明:

  1. 去重+0-00
  2. 去重NaN
  3. 对象new String("1")/a/{}不去重
  4. 数组[]不去重
  5. Symbol不去重

代码七(includes+reduce)

利用includes()方法检查新数组是否包含原数组的每一项

// 利用includes()方法检查新数组是否包含原数组的每一项
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/, [], []]

输出结果说明:

  1. 去重+0-00
  2. 去重NaN
  3. 对象new String("1")/a/{}不去重
  4. 数组[]不去重
  5. Symbol不去重

代码八(对象key)

利用了对象的key不可以重复的特性来进行去重

// 利用了对象的key不可以重复的特性来进行去重
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)]) {
        // 将对象序列化之后作为key来使用
        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), {}, []]

输出结果说明:

  1. 去重+0-00
  2. 去重NaN
  3. 去重对象new String("1"){};两个/a/全部被删除了
  4. 去重数组[]
  5. 去重Symbol

将不该去重的Symbol去重了;将两个/a/全部删除了

总结

方法结果说明
for循环暴力解法[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.对象new String(“1”)、/a/、{}不去重;4.数组[]不去重;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.对象new String(“1”)、/a/、{}不去重;4.数组[]不去重;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.对象new String(“1”)、/a/、{}不去重;4.数组[]不去重;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.两个NaN都会被删除;3.对象new String(“1”)、/a/、{}不去重;4.数组[]不去重;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"位置不同会导致去重不了 2.NaN不去重;3.对象new String(“1”)、/a/、{}不去重;4.数组[]不去重;5.sort()方法不支持处理含有Symbol的数组;
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.对象new String(“1”)、/a/、{}不去重;4.数组[]不去重;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.对象new String(“1”)、/a/、{}不去重;4.数组[]不去重;5.Symbol(1)不去重;
对象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.去重对象new String(“1”)、{};两个/a/全部被删除了;4.去重数组[];5.去重Symbol

上面只是简单结果的去重总结,具体的去重选择还需要根据我们业务场景来选择去重方法。

演示地址

可以去Github仓库查看演示代码

跟着大佬学系列

主要是日常对每个进阶知识点的摸透,跟着大佬一起去深入了解JavaScript的语言艺术。

后续会一直更新,希望各位看官不要吝啬手中的赞。

❤️ 感谢各位的支持!!!

❤️ 如果有错误或者不严谨的地方,请务必给予指正,十分感谢!!!

❤️ 喜欢或者有所启发,欢迎 star!!!

参考

原文地址

【跟着大佬学JavaScript】之数组去重(结果对比)

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要对一个list数组对象进行去重,有多种方法可以实现。 一种方法是使用HashSet。你可以创建一个HashSet对象,然后遍历原始list数组,将每个元素添加到HashSet中。由于HashSet的特性是不允许重复元素的存在,所以最终HashSet中的元素就是原始list数组去重后的结果。最后,你可以将HashSet转换回List类型。 示例代码: ```java private static void removeDuplicate(List<String> list) { HashSet<String> set = new HashSet<String>(list.size()); List<String> result = new ArrayList<String>(list.size()); for (String str : list) { if (set.add(str)) { result.add(str); } } list.clear(); list.addAll(result); } ``` 这段代码使用了HashSet来去重list数组中的元素,并将结果存储在另一个ArrayList中。最后,通过清空原始list数组,然后将去重后的结果重新添加到list数组中,实现了list数组的去重。 另一种方法是使用嵌套循环遍历,并使用条件判断来去重元素。在这个方法中,你需要使用两个嵌套的for循环来遍历list数组中的每个元素,并通过比较元素的值来判断是否重复。如果两个元素的值相同且它们的索引不同,那么就将其中一个元素从list数组中移除。 示例代码: ```java for (int i = 0; i < list.size(); i++) { for (int j = 0; j < list.size(); j++) { if(i != j && list.get(i) == list.get(j)) { list.remove(list.get(j)); } } } ``` 这段代码通过两个嵌套循环遍历list数组,并比较元素的值来判断是否重复。如果有重复元素,就使用list.remove()方法将重复的元素从list数组中移除。 除了以上两种方法,还可以使用Java 8的Stream API来对list数组进行去重。你可以使用stream().distinct()来获取去重后的list数组。 示例代码: ```java import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class ArrayListExample { public static void main(String[] args) { ArrayList<Integer> numbersList = new ArrayList<>(Arrays.asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8)); List<Integer> listWithoutDuplicates = numbersList.stream().distinct().collect(Collectors.toList()); System.out.println(listWithoutDuplicates); } } ``` 这段代码使用了Java 8的Stream API的distinct()方法来获取去重后的list数组,然后使用collect(Collectors.toList())将结果转换为List类型。 以上就是对list数组对象进行去重的几种方法。你可以根据具体的需求选择其中一种方法来实现。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [List数组去重的几种方法](https://blog.csdn.net/weixin_47847063/article/details/124264937)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值