Filter array using a condition in JavaScript
The filter() method was introduced in JavaScript in ES2015 (ES6). This is a straight forward post explaining how to use it.
The syntax of the Array.prototype.filter
method is
let newArray = arr.filter(callback(element[, index, [array]])[, thisArg])
The callback
is a function. Generally I use an arrow function for it.
The callback
function is invoked by the filter method for each and every element in the array. In each invocation an element of the array is passed to the callback
function along with the index of the element and the whole array itself.
Examples using arr.filter()
// Filtering the even numbers out of the array
const arr = [11, 245, 42, 3, 7, 8, 6, 9, 4, 8, 7, 9, 7, 7, 779, 3, 4, 7];
const evenArray = arr.filter(function(number) {
return number % 2 == 0;
});
// evenArray → [42, 8, 6, 4, 8, 4]
// If you want unique array you can use Set in JavaScript.
The above example can be written shortly using arrow function:
const arr = [11, 245, 42, 3, 7, 8, 6, 9, 4, 8, 7, 9, 7, 7, 779, 3, 4, 7];
const evenArray = arr.filter(n => n % 2 == 0); // evenArray → [42, 8, 6, 4, 8, 4]
const oddArray = arr.filter(n => n % 2); // oddArray → [11, 245, 3, 7, 9, 7, 9, 7, 7, 779, 3, 7]
Filtering array of objects
const arr = [
{id: 1, name: 'John', age: 13},
{id: 2, name: 'Smith', age: 46},
{id: 3, name: 'Doe', age: 53},
{id: 4, name: 'Stephen', age: 17},
{id: 5, name: 'Richard', age: 28},
{id: 6, name: 'Joshi', age: 6},
];
const eligibleToVote = arr.filter(user => user.age >= 18);
// eligibleToVote → consists 3 objects of users: Smith, Doe and Richard
Last Updated on
Comments