Skip to content

Filter values from Object Arrays in JavaScript

In this tutorial, we will learn how to use the JavaScript Array filter() method to filter elements in an array. The filter() method executes the function and return the new array only the original array that passes the condition provided. This doesn’t change the original array.

Lets consider the below object array for our understanding.

let students= [
    {name: 'Lokesh', grade: 'A', section : 'A'},
    {name: 'Ablilash', grade: 'C', section: 'A'},
    {name: 'Harry', grade: 'A', section: 'B'},
    {name: 'Potter', grade: 'B', section: 'D'},
    {name: 'John', grade: 'D', section: 'C'}
];

To extract an element from an array, we typically loop over the array using for loop, like the below:

let aSecStud= [];
for (let i = 0; i < students.length; i++) {
    if (students[i].section === 'A') {
        aSecStud.push(students[i]);
    }
}
console.log(aSecStud);

Output

[
{name: 'Lokesh', grade: 'A', section : 'A'},
{name: 'Ablilash', grade: 'C', section: 'A'}
]

In ECMAScript 5, filter() method makes the array extract easier. An array containing all the array elements that pass the test. If no elements pass the test it returns an empty array.

let aSecStud= students.filter(function (e) {
    return students.section === 'A';
});
console.log(aSecStud);

In Next Version Of Javascript ES6, It is even cleaner when you use the arrow function (=>).

let aSecStud = students.filter(stud=> stud.section === 'A');
console.log(aSecStud);

Internally, the filter() method iterates over each element of the array and passes each element to the callback function. If the callback function returns true, it includes the element in the return array.

Syntax

array.filter(function(currentValue, index, arr), thisValue)
ParameterDescription
currentValuecurrent element in the array that is being processed by the callback function.
indexIndex of the currentValue. Optional
arrobject being traversed. Optional
thisValueReferred as contextObject(Optional). If you pass this argument you can access using this keyword.

Example

function upperRange(value) {
       return value.grade === this.upper;
}

function lowerRange(value) {
       return value.grade === this.lower;
}

let range = {
    lower: 'D',
    upper: 'A'
};

let upperGrade= students.filter(upperRange, range);
Let lowerGrade =  students.filter(lowerRange, range);
console.log('Upper Grade Students:\n', upperGrade); 
console.log('Lower Grade Students:\n', lowerGrade ); 

Output

Upper Grade Students:
[
  {name: 'Lokesh', grade: 'A', section : 'A'},
  {name: 'Harry', grade: 'A', section: 'B'}
]
Lower Grade Students:
[
   {name: 'John', grade: 'D', section: 'C'}
]

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.