JavaScript数组filter()方法详解:语法、数据筛选与链式调用实战
本文详细介绍JavaScript中array.filter()方法的语法结构与返回值特性,并通过筛选偶数、高价值客户、无效用户记录及计算平均薪资增长等实际案例,演示如何利用filter进行数据筛选、清洗及链式调用,提升代码可读性与维护性。

一、为什么要使用array.filter()
该方法具备简洁、易用、语义清晰且扩展性强的特点。相较于for、forEach以及使用频率较低的while和do...while循环,filter能生成结构更清晰的代码,避免嵌套循环与回调带来的混乱感,使代码逻辑更加优雅易读。
追求编写优雅代码是程序员的目标。
array.filter()正如其名,充当过滤器的角色,语义直观,易于上手。
二、array.filter()的使用与技巧
2.1、基本语法
array.filter(callback(element, index, array), thisArg)
其中callback是对数组中每个元素执行的回调函数,接收三个参数:
- element:当前遍历到的元素
- index (可选):当前遍历到的索引
- array (可选):调用filter方法的原始数组
thisArg为执行callback时用作this的值。
2.2、返回值
返回一个新数组,其中包含所有通过测试的元素。
2.3、使用技巧
综上所述,array.filter()作为数组过滤器,不会修改原数组,而是返回一个新数组,常用于基础数据的筛选以适配特定场景。
应用场景:数据筛选、数据清洗和链式调用。
2.3.1、筛选数字数组中的偶数
最基础的示例,基于原始数据numbers数组,通过array.filter()生成一个仅包含偶数的新数组evenNumbers。
// 示例1:筛选数组中的偶数
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、数据筛选:筛选出高价值客户
假设有一个客户消费记录的数组,我们想要筛选出过去一年内消费总额超过10000元且订单数量超过5个的高价值客户。
// 示例2:筛选出高价值客户
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' }
]},
// ... 更多客户
];
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、数据清洗:移除无效的用户记录
假设我们有一个包含用户注册信息的数组,我们想要移除那些邮箱地址无效或密码长度不符合要求的用户记录。
// 示例3:移除无效的用户记录
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' },
// ... 更多用户
];
const validUsers = users.filter(user => {
// 使用正则表达式验证邮箱格式
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
// 密码长度至少为6个字符
return emailRegex.test(user.email) && user.password.length >= 6;
});
console.log(validUsers);2.3.4、链式调用:计算员工的平均薪资增长
假设我们有一个员工薪资记录的数组,我们想要找出过去两年内薪资增长超过10%的员工,并且计算他们的平均薪资增长百分比。
// 示例4:计算员工的平均薪资增长
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; // 转换为百分比
})
.reduce((totalGrowth, growth) => totalGrowth + growth, 0) / employees.length;
console.log(`The average salary growth over the past two years is: ${averageSalaryGrowth.toFixed(2)}%`);三、总结
使用array.filter()实现数据筛选、数据清洗和链式调用,相比for循环更加清晰且语义化强,能显著提升代码的可读性和可维护性。
到此这篇关于JavaScript中通过array.filter()实现数组的数据筛选、数据清洗和链式调用(JS数组过滤器的使用示例)的文章就介绍到这了,更多相关js array.filter()数组数据筛选内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!
JS处理含Emoji或中文的字符串转数组乱码问题
2026-11-05 16:12:28
JS怎么使用展开运算符合并对象
2026-11-05 14:42:18
ES6+环境下判断JS对象为空的简洁写法
2026-11-05 12:12:23
怎么通过replacer函数自定义JS中JSON的格式化输出
2026-11-05 11:19:44
JS正则表达式基础:字面量与RegExp构造函数的区别及常用元字符
2026-11-05 11:16:58
