js实现过滤
过滤数组中的元素
使用 Array.prototype.filter() 方法可以过滤数组中的元素。该方法接受一个回调函数,返回一个新数组,包含所有通过测试的元素。
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // [2, 4]
过滤对象数组
对于对象数组,可以根据对象的属性值进行过滤。
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 35 }
];
const youngUsers = users.filter(user => user.age < 30);
console.log(youngUsers); // [{ name: 'Alice', age: 25 }]
过滤字符串数组
可以过滤字符串数组,例如筛选包含特定字符的字符串。
const words = ['apple', 'banana', 'grape', 'orange'];
const filteredWords = words.filter(word => word.includes('ap'));
console.log(filteredWords); // ['apple', 'grape']
使用索引过滤
filter 方法的回调函数可以接收三个参数:当前元素、索引和数组本身。可以利用索引进行过滤。
const numbers = [10, 20, 30, 40, 50];
const filteredNumbers = numbers.filter((num, index) => index % 2 === 0);
console.log(filteredNumbers); // [10, 30, 50]
过滤空值
可以使用 filter 方法移除数组中的空值(如 null、undefined 或空字符串)。
const mixedArray = [0, 1, '', 'hello', null, undefined, false];
const truthyValues = mixedArray.filter(Boolean);
console.log(truthyValues); // [1, 'hello']
链式过滤
可以将多个 filter 方法链式调用,实现多重过滤条件。
const products = [
{ name: 'Laptop', price: 1000, stock: 5 },
{ name: 'Phone', price: 500, stock: 10 },
{ name: 'Tablet', price: 300, stock: 0 }
];
const availableAffordableProducts = products
.filter(product => product.stock > 0)
.filter(product => product.price < 800);
console.log(availableAffordableProducts); // [{ name: 'Phone', price: 500, stock: 10 }]





