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

    来源:https://www.w3cplus.com/javascript/javascript-tips.html

    1、数组去重  

    ES6提供了几种简洁的数组去重的方法,但该方法并不适合处理非基本类型的数组。对于基本类型的数组去重,可以使用... new Set()来过滤掉数组中重复的值,创建一个只有唯一值的新数组。

    const array = [1, 1, 2, 3, 5, 5, 1] 
    const uniqueArray = [...new Set(array)]; 
    console.log(uniqueArray); 
    > Result:(4) [1, 2, 3, 5]

    这是ES6中的新特性,在ES6之前,要实现同样的效果,我们需要使用更多的代码。该技巧适用于包含基本类型的数组:undefinednullbooleanstringnumber。如果数组中包含了一个object,function或其他数组,那就需要使用另一种方法。

    除了上面的方法之外,还可以使用Array.from(new Set())来实现:

    const array = [1, 1, 2, 3, 5, 5, 1] 
    Array.from(new Set(array)) 
    > Result:(4) [1, 2, 3, 5]
    

      另外,还可以使用Array.filter indexOf()来实现

    const array = [1, 1, 2, 3, 5, 5, 1] 
    array.filter((arr, index) => array.indexOf(arr) === index) 
    > Result:(4) [1, 2, 3, 5]
    

      注意,indexOf()方法将返回数组中第一个出现的数组项。这就是为什么我们可以在每次迭代中将indexOf()方法返回的索引与当索索引进行比较,以确定当前项是否重复。

  • 相关阅读:
    根据表生成接收(zml)
    删除指定日期,指定设备的排产记录(zml)
    1029 Median
    1027 Colors in Mars (20 分)进制转换
    1028 List Sorting 排序
    1025 PAT Ranking
    1024 Palindromic Number(大数加法)
    1023 Have Fun with Numbers
    1022 Digital Library
    逆序打印乘法表
  • 原文地址:https://www.cnblogs.com/arealy/p/11175719.html
Copyright © 2011-2022 走看看