一、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)
})