【js學習】js中filter過濾用法總結


定義和用法

filter() 方法創建一個新的數組,新數組中的元素是通過檢查指定數組中符合條件的所有元素。

注意: filter() 不會對空數組進行檢測。

注意: filter() 不會改變原始數組。

 

語法

array.filter(function(currentValue,index,arr), thisValue)

參數說明

 

參數 描述
function(currentValue, index,arr) 必須。函數,數組中的每個元素都會執行這個函數
函數參數:
參數 描述
currentValue 必須。當前元素的值
index 可選。當期元素的索引值
arr 可選。當期元素屬於的數組對象
thisValue 可選。對象作為該執行回調時使用,傳遞給函數,用作 "this" 的值。
如果省略了 thisValue ,"this" 的值為 "undefined"

 

首先回顧一下filter的作用:過濾數組中符合條件的元素

基本用法

1
2
3
let arr = [1, 3, 5, 8]
let arrFilter = arr.filter(ele => ele > 4)
console.log(arrFilter) // [5, 8]

另外也可以用來過濾對象數組中符合條件的對象,eg:

1
2
3
4
5
6
7
8
9
10
11
12
13
let arrObj = [{
name: 'aa', age: 13
}, {
name: 'bb', age: 23
}, {
name: 'cc', age: 18
}, {
name: 'dd', age: 11
}, {
name: 'ee', age: 28
}]
let arrObjFilter = arrObj.filter(ele => ele.age > 18)
console.log(arrObjFilter) // [{name: 'bb', age: 23}, {name: 'ee', age: 28}]

進階用法

數組去重(有點過時)

1
2
3
4
5
let arr = [1, 2, 3, 2, 3, 4]
let arrFilter = arr.filter((ele, index, arr) => {
return arr.indexOf(ele) === index
})
console.log(arrFIlter)

目前比較常用的方法是使用ES6的set完成,eg:

1
2
3
let arr = [1, 2, 3, 2, 3, 4]
let arrFilter = [...new Set(arr)]
console.log(arrFilter)

數組中的空字符去除

1
2
3
4
5
let arr = ['1', '2', '3', '', null, undefined, ' ', '4']
let arrFilter = arr.filter((ele, index, arr) => {
return ele && ele.trim()
})
console.log(arrFIlter)

高級用法

結合map使用可以先過濾出符合條件的對象然后去除某些不需要的字段,比如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 需求: 年齡大於18的姓名
let arrObj = [{
name: 'aa', age: 13
}, {
name: 'bb', age: 23
}, {
name: 'cc', age: 18
}, {
name: 'dd', age: 11
}, {
name: 'ee', age: 28
}]
let arrObjFilter = arrObj.filter(ele => ele.age > 18).map(ele => {
return ele.name
})
console.log(arrObjFilter) // ['bb', 'ee']

 

 

filter()

簡單講filter就是一個數組過濾器,參數接收一個函數,數組的每一項經過函數過濾,返回一個符合過濾條件的新數組

函數接收三個參數:

  • item (當前遍歷的數組項)
  • i (當前項索引)
  • arr (調用filter數組本身)
 // 需求找到數組內偶數
復制代碼
 let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

        let newArr = arr.filter((item, i, arr) => {
            //函數本身返回布爾值,只有當返回值為true時,當前項存入新數組。
            return item % 2 == 0
        })
        console.log(newArr)
復制代碼

 

再來一個應用,巧妙地用filter結合indexof實現去重
indexOf在js中有着重要的作用,可以判斷一個元素是否在數組中存在,或者判斷一個字符是否在字符串中存在,如果存在返回該元素或字符第一次出現的位置的索引,不存在返回-1。
復制代碼
let arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 2, 3, 4, 5, 6, 7]

        let newArr = arr1.filter(function(item, i, self) {
            let a = self.indexOf(item)
            console.log(`item----${item},self.indexOf(item)---${a},i----${i}`)
            return self.indexOf(item) === i;
        });

        console.log(newArr) //[1, 2, 3, 4, 5, 6, 7, 8]
復制代碼

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM