4 Different ways to filter an array
Sunil Soundarapandian
UI Architect ? Frontend Team Leader ? Engineering Manager ? Product Innovator ? Angular ? ReactJs ? Typescript
If you are new to the JavaScript world here are 4 different ways to filter data from an array.
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(number => number % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]
2. Using the map() method - The map() method creates a new array with the results of calling a provided function on every element in the calling array. For example:
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.map(number => number % 2 === 0 ? number : null).filter(Boolean);
console.log(evenNumbers); // Output: [2, 4]
3. Using the reduce() method - The reduce() method applies a function against an accumulator and each element in the array to reduce it to a single value. For example:
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.reduce((accumulator, number) => {
? if (number % 2 === 0) {
? ? return [...accumulator, number];
? } else {
? ? return accumulator;
? }
}, []);
console.log(evenNumbers); // Output: [2, 4]
4. Using a for loop - A for loop can also be used to filter an array. For example:
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = [];
for (let i = 0; i < numbers.length; i++) {
? if (numbers[i] % 2 === 0) {
? ? evenNumbers.push(numbers[i]);
? }
}
console.log(evenNumbers); // Output: [2, 4]