js实现筛选
使用 filter() 方法筛选数组
filter() 是 JavaScript 数组的高阶函数,用于根据条件筛选元素。它返回一个新数组,包含所有满足条件的元素。
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // 输出 [2, 4]
自定义筛选函数实现
通过遍历数组并手动检查条件,可以自定义筛选逻辑。这种方式适用于更复杂的筛选需求。
function customFilter(array, condition) {
const result = [];
for (let item of array) {
if (condition(item)) {
result.push(item);
}
}
return result;
}
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 }
];
const youngUsers = customFilter(users, user => user.age < 30);
console.log(youngUsers); // 输出 [{ name: 'Alice', age: 25 }]
结合 reduce() 实现筛选
reduce() 方法可以灵活地处理数组筛选,尤其适合需要累积结果的场景。
const words = ['apple', 'banana', 'grape', 'kiwi'];
const longWords = words.reduce((acc, word) => {
if (word.length > 5) acc.push(word);
return acc;
}, []);
console.log(longWords); // 输出 ['banana', 'grape']
使用 find() 或 findIndex() 筛选单个元素
find() 返回第一个满足条件的元素,findIndex() 返回其索引。适用于查找唯一匹配项的场景。
const inventory = [
{ id: 1, name: 'Laptop', inStock: true },
{ id: 2, name: 'Mouse', inStock: false }
];
const availableItem = inventory.find(item => item.inStock);
console.log(availableItem); // 输出 { id: 1, name: 'Laptop', inStock: true }
多条件筛选
通过组合多个条件,可以实现复杂筛选逻辑。例如,筛选数组中同时满足两个条件的元素。
const products = [
{ name: 'Phone', price: 500, category: 'electronics' },
{ name: 'Shirt', price: 20, category: 'clothing' }
];
const filteredProducts = products.filter(
product => product.price < 100 && product.category === 'clothing'
);
console.log(filteredProducts); // 输出 [{ name: 'Shirt', price: 20, category: 'clothing' }]
筛选并转换数据
在筛选的同时对数据进行转换,例如提取对象的特定属性。

const students = [
{ id: 1, score: 85 },
{ id: 2, score: 90 }
];
const highScores = students
.filter(student => student.score >= 90)
.map(student => student.id);
console.log(highScores); // 输出 [2]






