一、基本介紹
數組過濾是指根據特定條件從數組中篩選出符合條件的元素形成新數組,這個過程就是數組過濾。在JavaScript中,可以使用filter()方法完成數組過濾的操作。
此方法創建一個新的數組,其包含通過給定函數實現的測試的所有元素。
filter()方法不會改變原始數組
const array = [1, 2, 3, 4, 5]; const newArray = array.filter(element => element > 3); console.log(newArray);// [4,5]>
二、基本語法
filter()方法有兩個參數,分別是回調函數和可選參數this。回調函數一共接受三個參數:
- 數組當前項的值
- 當前項的下標
- 當前操作的數組
回調函數必須返回一個布爾類型。如果為true,則保留該項並將其添加到新的輸出數組中,如果為false,則刪除該項。
var new_array = arr.filter(callback(element[, index[, array]])[, thisArg])
三、常見操作
1.filter()方法實現數字去重
數組去重是一項經常需要完成的操作,JS中使用filter()方法可以快速去重一個數字數組,比如使用 Set() 方法也可以實現去重,但filter()方法更方便易用。
const numbers = [1,2,2,3,4,4,5]; let uniqueNumbers = numbers.filter((value, index, array) => array.indexOf(value) === index); console.log(uniqueNumbers); // [1, 2, 3, 4, 5]
2.filter()方法實現對象數組條件過濾
objects數組是一個具有結構化數據的對象數組。可以使用filter方法對此類型的數組進行過濾。
從對象數組中獲取符合特定屬性值的對象,只需在回調內對該值進行比較即可完成對象數組的篩選。
const users = [ { id: 1, name: 'Alex', age: 27 }, { id: 2, name: 'Max', age: 20 }, { id: 3, name: 'Jack', age: 25 } ]; const result = users.filter(user => user.age > 23); console.log(result);// [{ id: 1, name: 'Alex', age: 27 }, { id: 3, name: 'Jack', age: 25 }]
3.filter()方法實現模糊關鍵字過濾
filter還可以根據數組元素中的字符進行模糊過濾,比如刪除名字中包含某個字符的對象。這個技巧很有用,因為你不一定總能確切的知道要篩選的值。
const fruits = ['apple', 'banana', 'citrus', 'peach', 'grape']; const result = fruits.filter(fruit => fruit.includes('a')); console.log(result);// ['apple', 'banana', 'grape']
四、結束語
使用filter()方法能快速方便的對數組進行過濾操作,我們可以根據需要自由的組合使用filter()方法來實現複雜的需求。
本篇文章介紹到常見操作,可能還有一些不常見的用法,需要動手實踐多多嘗試。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/182173.html