今日份数组去重

126 阅读2分钟

这是我参与8月更文挑战的第2天,活动详情查看:8月更文挑战” 数组去重,老声常谈的问题了。一般来说,面试较多,可能偶尔在工作中会遇见。

  1. 第一个就是ES6 不得不说的set很强大。这就得从set的概念来说了,set本身是集合,有唯一性,所以我们可以利用这一特性。
const arr2=['1','null','undefined','2','{}','{}','1','2','3','4']
const arr=[...new Set(arr2)]
console.log(arr) //[ '1', 'null', 'undefined', '2', '{}', '3', '4' ]
  1. 使用数组API(indexof) indexof是匹配和数组中相同元素的数组下标,返回匹配第一个相同的数组下标。如果没有就返回-1.
const arr2=['1','null','undefined','2','{}','{}','1','2','3','4','undefined','null']
const arr3=[]
 arr2.forEach(val=>{
    if(arr3.indexOf(val)==-1){
        arr3.push(val)
    }
 })
 console.log(arr3) //[ '1', 'null', 'undefined', '2', '{}', '3', '4' ]

3.和indexof差不多的就是includes,includes也是匹配相同的元素,只不过返回的是Boolean值,如果匹配到就为true,反之为false。

const arr2=['1','null','undefined','2','{}','{}','1','2','3','4','undefined','null']
const arr3=[]
 arr2.forEach(val=>{
    if(!arr3.includes(val)){
        arr3.push(val)
    }
 })
 console.log(arr3) //[ '1', 'null', 'undefined', '2', '{}', '3', '4' ] 结果和上面的indexof相同

4.filter方法 filter()方法创建一个新的数组,新数组中的元素是通过检查指定数组中是否包含符合条件的元素。 语法:

数组.filter(function(currentValue,index,arr),thisValue)

第一个参数currentValue是当前元素,index是当前元素的数组下标,arr就是当前数组了,index和arr都是可选的,currentValue是必选的,thisValue也是可选的,用作this的值

const arr2=['1','null','undefined','2','{}','{}','1','2','3','4','undefined','null']
 function unique(arr) {
    //定义常量 res,值为一个Map对象实例
    const res = new Map();
    
    //返回arr数组过滤后的结果,结果为一个数组
    //过滤条件是,如果res中没有某个键,就设置这个键的值为1,这是ES6的新写法
    return arr.filter((a) => !res.has(a) && res.set(a, 1))
}
const arr=unique(arr2)
console.log(arr) //[ '1', 'null', 'undefined', '2', '{}', '3', '4' ]

5.还有就是最常用的for循环了,这个就略过吧,其实这个的思想和第一个和第二个一样

好了,瑞思拜