Array filtering in JavaScript is a powerful feature that can be used creatively and practically.
Here are some innovative uses of the array.filter method:
1. Removing Duplicates
const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = numbers.filter((value, index, self) => self.indexOf(value) === index);
// uniqueNumbers: [1, 2, 3, 4, 5]
2. Finding Prime Numbers
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const isPrime = num => {
for (let i = 2, s = Math.sqrt(num); i <= s; i++)
if (num % i === 0) return false;
return num > 1;
};
const primeNumbers = numbers.filter(isPrime);
// primeNumbers: [2, 3, 5, 7]
3. Filtering Objects by Property
const users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 30 },
{ name: 'Charlie', age: 25 }
];
const age25 = users.filter(user => user.age === 25);
// age25: [{ name: 'Alice', age: 25 }, { name: 'Charlie', age: 25 }]
4. Excluding Falsy Values
const values = [0, 1, false, 2, '', 3, null, undefined, 4];
const truthyValues = values.filter(Boolean);
// truthyValues: [1, 2, 3, 4]
5. Filtering Nested Arrays
const nestedArrays = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const flattenedAndFiltered = nestedArrays.flat().filter(num => num > 5);
// flattenedAndFiltered: [6, 7, 8, 9]
6. Filtering Unique Values in Nested Arrays
const arrays = [[1, 2, 3], [3, 4, 5], [5, 6, 7]];
const uniqueValues = [...new Set(arrays.flat())];
// uniqueValues: [1, 2, 3, 4, 5, 6, 7]
7. Filtering by Date Range
const events = [
{ name: 'Event 1', date: new Date('2023-01-01') },
{ name: 'Event 2', date: new Date('2023-06-01') },
{ name: 'Event 3', date: new Date('2023-12-01') }
];
const startDate = new Date('2023-01-01');
const endDate = new Date('2023-06-30');
const filteredEvents = events.filter(event => event.date >= startDate && event.date <= endDate);
// filteredEvents: [{ name: 'Event 1', date: new Date('2023-01-01') }, { name: 'Event 2', date: new Date('2023-06-01') }]
8. Filtering with Multiple Conditions
const products = [
{ name: 'Laptop', price: 1000, inStock: true },
{ name: 'Phone', price: 500, inStock: false },
{ name: 'Tablet', price: 300, inStock: true }
];
const availableExpensiveProducts = products.filter(product => product.inStock && product.price > 400);
// availableExpensiveProducts: [{ name: 'Laptop', price: 1000, inStock: true }]
9. Filtering Array of Strings by Length
const words = ['apple', 'banana', 'cherry', 'date'];
const longWords = words.filter(word => word.length > 5);
// longWords: ['banana', 'cherry']
10. Filtering Non-Numeric Values
const mixedValues = [1, 'two', 3, 'four', 5];
const numericValues = mixedValues.filter(value => typeof value === 'number');
// numericValues: [1, 3, 5]
Thank you for reading!
Top comments (0)