数组去重方法———filter()与indexOf()结合使用

一、filter()

filter用于对数组进行过滤。
filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
注意:

  • filter() 不会对空数组进行检测;不会改变原始数组

  • 返回数组,包含了符合条件的所有元素。如果没有符合条件的元素则返回空数组。
    用法:
    filter() 方法用于把Array中的某些元素过滤掉,然后返回剩下的未被过滤掉的元素。

具体参数:

二、indexof()

检测当前值在数组中第一次出现的位置索引.
接收两个参数:要查找的项和(可选的)表示查找起点位置的索引。
indexOf():从数组的开头(位置 0)开始向后查找。
返回要查找的项在数组中的位置,或者在没找到的情况下返回-1。

三、filter()中使用 indexOf()去重

在filter()中使用:对indexOf得到的数组元素位置和按顺序排列的数组位置做比较,两个相同就是不重复元素。

const array = [2, 2, 'a', 'a', true, true, 15, 17]
const newArr = array.filter((item, i, arr) => {
      return arr.indexOf(item) === i
    })
console.log(newArr);//打印 [2, 'a', true, 15, 17]
 
//-------------------------------------------------------------------------
 
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 4, 5, 6, 7, 9,]
const newArr = array.filter((item, i, arr) => {
      return arr.indexOf(item) === i
    })
console.log(newArr);// 打印 [1, 2, 3, 4, 5, 6, 7, 8, 9]
  let ARR = [1, 2, 3, 4, 5, 1, 2, 3];
  let  arrs = ARR.filter((value, index ,ARR)=> ARR.indexOf(value)==index) 
  console.log(arrs); //[1, 2, 3, 4, 5]
arr1.filter((item, index) => {
        //这里打印了arr1.indexOf(item)
        //值为0,1,2,3,2,5,6,7,8,7,6,11,8
        console.log(arr1.indexOf(item))
        //这里打印了index
        //值为0,1,2,3,4,5,6,7,8,9,10,11,12,
        console.log(index)
        return index == arr1.indexOf(item)
    })
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值