Hai phương pháp chính: Array.filter() (native) và _.filter() (Lodash/Underscore). Cả hai trả về mảng mới chứa các phần tử pass test.
1. Array.filter() — Native (Khuyên dùng)
<script>
const salaries = [12000, 13000, 15000, 78000, 43000];
const highSalaries = salaries.filter(salary => salary > 20000);
document.write(highSalaries); // 78000,43000
</script>
Callback parameters
arr.filter((value, index, array) => {
// value: phần tử hiện tại
// index: chỉ số
// array: mảng gốc
return true/false; // Giữ nếu true
});
2. _.filter() — Lodash/Underscore
Tương tự nhưng hỗ trợ thêm iteratee shorthand (string, object, property).
const users = [
{ name: 'Alice', active: true },
{ name: 'Bob', active: false },
{ name: 'Charlie', active: true }
];
// Native
users.filter(u => u.active);
// Lodash shorthand
_.filter(users, 'active'); // [{name:'Alice',active:true}, {name:'Charlie',active:true}]
_.filter(users, { active: true }); // Same
_.filter(users, ['active', true]); // Same
_.filter(users, u => u.name.startsWith('A'));
So sánh
| Đặc điểm | Array.filter() | _.filter() |
|---|---|---|
| Dependency | Không | Lodash/Underscore |
| Shorthand iteratee | Không | Có (string, object, array) |
| Hiệu suất | Native, tối ưu | Tương đương |
| Consistency | Chỉ array | Cũng làm việc với object (trả về array values) |
Ví dụ nâng cao: Filter với nhiều điều kiện
const products = [
{ name: 'Laptop', price: 1000, category: 'tech', inStock: true },
{ name: 'Phone', price: 500, category: 'tech', inStock: false },
{ name: 'Book', price: 20, category: 'edu', inStock: true }
];
// Native: combine conditions
const affordableTechInStock = products.filter(p =>
p.category === 'tech' && p.price < 800 && p.inStock
);
// Lodash: _.filter với matches property
_.filter(products, { category: 'tech', inStock: true })
.filter(p => p.price < 800);
find() vs filter()
find(): Trả về phần tử đầu tiên pass test (hoặc undefined).filter(): Trả về mảng tất cả phần tử pass test.