ES6 JavaScript
In this ES6 tutorial we are going to learn about the array filter method. So, let's get started.
In the previous tutorial ES6 - Array map method we talked about Map method and how it iterates over all the elements of an array and returns a new array with the same number of elements like the original array that it was iterating over.
Filter method also iterates over all the elements of an array but based on some logic we can filter out some of the elements from the original array and return a new array.
Let's say we have an array of positive integer values and we want to filter all the even numbers. To solve this we take help of the filter method.
const arr = [1, 2, 3, 4, 5];
const even = arr.filter(element => {
return element % 2 === 0;
});
console.log(even);
Let's say we have an array of objects. Each object represents a fruits and we want to filter out all out-of-stock fruits from the array.
For this we will write the following code.
const fruits = [
{ name: 'Mango', inStock: false },
{ name: 'Apple', inStock: true },
{ name: 'Orange', inStock: true },
{ name: 'Banana', inStock: false }
];
const outOfStockFruits = fruits.filter(fruit => !fruit.inStock);
console.log(outOfStockFruits);
All right this brings us to the end of this tutorial. I hope you will find this and other tutorial useful. See you in the next tutorial.
ADVERTISEMENT