JavaScript中通過(guò)array.filter()實(shí)現(xiàn)數(shù)組的數(shù)據(jù)篩選、數(shù)據(jù)清洗和鏈?zhǔn)秸{(diào)用(JS數(shù)組過(guò)濾器的使用示例)

一、為什么要使用array.fifler()
因?yàn)樗?jiǎn)單,好用,清晰,可拓展性強(qiáng),而且比f(wàn)or、foreach還有非常不常用的while、do...while高級(jí),代碼清晰,可讀性強(qiáng),代碼就看起來(lái)很優(yōu)雅,如果都是嵌套循環(huán)和嵌套回調(diào),看起來(lái)就是一團(tuán)亂麻,可讀性差,很不優(yōu)雅。
要做優(yōu)雅的程序員,寫(xiě)優(yōu)雅的代碼。
array.fifler()方法就像名字一樣,他就是一個(gè)過(guò)濾器,比較語(yǔ)義化,上手較快。
二、array.fifler()的使用與技巧
2.1、基本語(yǔ)法
array.filter(callback(element, index, array), thisArg)
其中callback回調(diào)函數(shù)對(duì)每個(gè)數(shù)組元素執(zhí)行的函數(shù),接受三個(gè)參數(shù):
- element:當(dāng)前遍歷到的元素
- index (可選):當(dāng)前遍歷到的索引
- array (可選):調(diào)用 filter 的數(shù)組本身
thisArg是執(zhí)行 callback 時(shí)用作 this 的值。
2.2、返回值
一個(gè)新的數(shù)組,包含通過(guò)測(cè)試的元素。
2.3、使用技巧
綜上所述,array.fifler()就是一個(gè)數(shù)組的過(guò)濾器,同時(shí)不影響數(shù)組本身的樣子,返回的是一個(gè)新的數(shù)組,常用于對(duì)基礎(chǔ)數(shù)據(jù)進(jìn)行篩選,以適用于特定的情況。
應(yīng)用場(chǎng)景:數(shù)據(jù)篩選、數(shù)據(jù)清洗和鏈?zhǔn)秸{(diào)用。
2.3.1、篩選數(shù)字?jǐn)?shù)組中的偶數(shù)
最基礎(chǔ)的例子,基于原始數(shù)據(jù)numbers數(shù)組,通過(guò)array.fifler()生成一個(gè)只含偶數(shù)的新數(shù)組evenNumbers。
// 示例1:篩選數(shù)組中的偶數(shù) const numbers = [1, 2, 3, 4, 5, 6]; const evenNumbers = numbers.filter(number => number % 2 === 0); console.log(evenNumbers); // [2, 4, 6]
2.3.2、數(shù)據(jù)篩選:篩選出高價(jià)值客戶(hù)
假設(shè)有一個(gè)客戶(hù)消費(fèi)記錄的數(shù)組,我們想要篩選出過(guò)去一年內(nèi)消費(fèi)總額超過(guò)10000元且訂單數(shù)量超過(guò)5個(gè)的高價(jià)值客戶(hù)。
// 示例2:篩選出高價(jià)值客戶(hù)
const customers = [
{ id: 1, name: 'Alice', orders: [
{ amount: 1200, date: '2023-05-15' },
{ amount: 2500, date: '2023-07-22' },
{ amount: 1800, date: '2023-08-05' }
]},
{ id: 2, name: 'Bob', orders: [
{ amount: 9000, date: '2023-03-01' },
{ amount: 2200, date: '2023-09-12' }
]},
{ id: 3, name: 'Charlie', orders: [
{ amount: 750, date: '2023-02-17' },
{ amount: 1100, date: '2023-04-03' },
{ amount: 1500, date: '2023-05-09' },
{ amount: 1300, date: '2023-06-21' }
]},
{ id: 4, name: 'David', orders: [
{ amount: 2000, date: '2023-01-05' },
{ amount: 1700, date: '2023-02-20' },
{ amount: 2300, date: '2023-03-18' }
]},
{ id: 5, name: 'Eve', orders: [
{ amount: 3500, date: '2023-04-08' },
{ amount: 4200, date: '2023-05-22' }
]},
{ id: 6, name: 'Frank', orders: [
{ amount: 550, date: '2023-03-02' },
{ amount: 850, date: '2023-08-16' }
]},
// ... 更多客戶(hù)
];
const highValueCustomers = customers.filter(customer => {
const totalSpent = customer.orders.reduce((sum, order) => {
const orderDate = new Date(order.date);
const oneYearAgo = new Date();
oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);
return sum + (orderDate >= oneYearAgo ? order.amount : 0);
}, 0);
return totalSpent > 10000 && customer.orders.length > 5;
});
console.log(highValueCustomers);2.3.3、數(shù)據(jù)清洗:移除無(wú)效的用戶(hù)記錄
假設(shè)我們有一個(gè)包含用戶(hù)注冊(cè)信息的數(shù)組,我們想要移除那些郵箱地址無(wú)效或密碼長(zhǎng)度不符合要求的用戶(hù)記錄。
// 示例3:移除無(wú)效的用戶(hù)記錄
const users = [
{ id: 1, name: 'Alice', email: 'alice', password: 'alice123' },
{ id: 2, name: 'Bob', email: 'bob@example.com', password: 'b' },
{ id: 3, name: 'Charlie', email: 'charlie@work.com', password: 'Ch@rl1e!' },
{ id: 4, name: 'Diana', email: 'diana', password: 'D123456' },
{ id: 5, name: 'Edward', email: 'edward@', password: 'edwardpassword' },
{ id: 6, name: 'Fiona', email: 'fiona123', password: 'fionaP@ss' },
{ id: 7, name: 'George', email: 'george@example.com', password: 'g' },
{ id: 8, name: 'Hannah', email: 'hannah@hann.com', password: 'HannahPass123!' },
{ id: 9, name: 'Ivan', email: 'ivan', password: 'IvanIvanIvan' },
{ id: 10, name: 'Julia', email: 'julia@julia', password: 'ju@123' },
// ... 更多用戶(hù)
];
const validUsers = users.filter(user => {
// 使用正則表達(dá)式驗(yàn)證郵箱格式
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
// 密碼長(zhǎng)度至少為6個(gè)字符
return emailRegex.test(user.email) && user.password.length >= 6;
});
console.log(validUsers);2.3.4、鏈?zhǔn)秸{(diào)用:計(jì)算員工的平均薪資增長(zhǎng)
假設(shè)我們有一個(gè)員工薪資記錄的數(shù)組,我們想要找出過(guò)去兩年內(nèi)薪資增長(zhǎng)超過(guò)10%的員工,并且計(jì)算他們的平均薪資增長(zhǎng)百分比。
// 示例4:計(jì)算員工的平均薪資增長(zhǎng)
const employees = [
{ id: 1, name: 'Alice', salary: 5000, salaryTwoYearsAgo: 4000 },
{ id: 2, name: 'Bob', salary: 6500, salaryTwoYearsAgo: 7000 },
{ id: 3, name: 'Charlie', salary: 8000, salaryTwoYearsAgo: 6500 },
{ id: 4, name: 'David', salary: 7200, salaryTwoYearsAgo: 6000 },
{ id: 5, name: 'Eve', salary: 9500, salaryTwoYearsAgo: 8200 },
{ id: 6, name: 'Frank', salary: 6800, salaryTwoYearsAgo: 5800 },
{ id: 7, name: 'Grace', salary: 7800, salaryTwoYearsAgo: 7200 },
{ id: 8, name: 'Heidi', salary: 9200, salaryTwoYearsAgo: 8500 },
{ id: 9, name: 'Ivan', salary: 6300, salaryTwoYearsAgo: 5500 },
{ id: 10, name: 'Judy', salary: 8600, salaryTwoYearsAgo: 7800 },
// ... 更多員工
];
const averageSalaryGrowth = employees
.filter(employee => {
const growth = (employee.salary - employee.salaryTwoYearsAgo) / employee.salaryTwoYearsAgo;
return growth > 0.10;
})
.map(employee => {
const growth = (employee.salary - employee.salaryTwoYearsAgo) / employee.salaryTwoYearsAgo;
return growth * 100; // 轉(zhuǎn)換為百分比
})
.reduce((totalGrowth, growth) => totalGrowth + growth, 0) / employees.length;
console.log(`The average salary growth over the past two years is: ${averageSalaryGrowth.toFixed(2)}%`);三、總結(jié)
用array.filter()來(lái)實(shí)現(xiàn)數(shù)據(jù)篩選、數(shù)據(jù)清洗和鏈?zhǔn)秸{(diào)用,相對(duì)于for循環(huán)更加清晰,語(yǔ)義化強(qiáng),能顯著提升代碼的可讀性和可維護(hù)性。
到此這篇關(guān)于JavaScript中通過(guò)array.filter()實(shí)現(xiàn)數(shù)組的數(shù)據(jù)篩選、數(shù)據(jù)清洗和鏈?zhǔn)秸{(diào)用(JS數(shù)組過(guò)濾器的使用示例)的文章就介紹到這了,更多相關(guān)js array.filter()數(shù)組數(shù)據(jù)篩選內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
JS簡(jiǎn)單實(shí)現(xiàn)點(diǎn)擊按鈕或文字顯示遮罩層的方法
這篇文章主要介紹了JS簡(jiǎn)單實(shí)現(xiàn)點(diǎn)擊按鈕或文字顯示遮罩層的方法,涉及javascript鼠標(biāo)事件響應(yīng)及頁(yè)面元素屬性動(dòng)態(tài)操作相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-04-04
Javascript絕句欣賞 一些經(jīng)典的js代碼
Javascript絕句欣賞 一些經(jīng)典的js代碼整理,學(xué)習(xí)js的朋友可以參考下2012-02-02
JS高級(jí)調(diào)試技巧:捕獲和分析 JavaScript Error詳解
前端工程師都知道 JavaScript 有基本的異常處理能力。我們可以 throw new Error(),瀏覽器也會(huì)在我們調(diào)用 API 出錯(cuò)時(shí)拋出異常。但估計(jì)絕大多數(shù)前端工程師都沒(méi)考慮過(guò)收集這些異常信息2014-03-03
js 通過(guò)html()及text()方法獲取并設(shè)置p標(biāo)簽的顯示值
這篇文章主要介紹了js 通過(guò)html()及text()方法獲取并設(shè)置p標(biāo)簽的顯示值,需要的朋友可以參考下2014-05-05
spirngmvc js傳遞復(fù)雜json參數(shù)到controller的實(shí)例
下面小編就為大家分享一篇spirngmvc js傳遞復(fù)雜json參數(shù)到controller的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-03-03
微信小程序使用setData修改數(shù)組中單個(gè)對(duì)象的方法分析
這篇文章主要介紹了微信小程序使用setData修改數(shù)組中單個(gè)對(duì)象的方法,結(jié)合具體實(shí)例形式分析了setData進(jìn)行數(shù)組修改的相關(guān)操作技巧與注意事項(xiàng),需要的朋友可以參考下2018-12-12

