How to Filter an Array of Objects in React

Filtering an Array of Objects in React is the way to get the value or element you want. To do that, this article will show you how to use a very popular and extremely simple method. it’s filter()

Filter an Array of Objects in React

Syntax of filter() function

arrayObject.filter(callback, contextObject);

arrayObject: your object array name.

Callback, contextObject: The filter() method accepts two named arguments: a callback function and an options object.

The method returns a new array containing all the elements that pass the test performed by the callback() function.

Note: So that you know, the filter() method does not change the original array.

Use the filter function

Suppose we have an array of objects like this:

const people = [
  {
    name: 'Luna',
    age: 21,
  },
  {
    name: 'Serry',
    age: 45,
  },
  {
    name: 'Anna',
    age: 18,
  },
  {
    name: 'Jony',
    age: 49,
  },
  {
    name: 'George',
    age: 30,
  }
];

To find information about people over 25, the filter() method allows you to do this more concisely and clearly than a loop.

let peopleInfor = people.filter(function(e) {
    return e.age > 25;
});

console.log(peopleInfor);

Inside the function, we checked if this person’s age was greater than 25. ‘e' is the current element in the array being processed by the callback function

If so, the function returns true. If not, it returns false.

Output:

[{name: "Serry", age: 45}, {name: "Jony", age: 49}, {name: "George", age: 30} ]

Alternatively, you can use the arrow function (in ES6) and write “Clean code” like this:

let peopleInfor = people.filter(e => e.age > 25);
console.log(peopleInfor);

Output:

[{name: "Serry", age: 45}, {name: "Jony", age: 49}, {name: "George", age: 30} ]

Bonus trick

Since the filter() method returns a new array, you can chain the results with other iterative methods like map().

let peopleInfor = people.filter(function(e) {
    return e.age > 25;
}).map(e => console.log(e.name + ':' + e.age));

As a result, we get:

Serry:45
Jony:49
George:30

Summary

So, following this tutorial, you learned how to use the filter() method to filter an array of objects in React according to the test condition provided by a callback function.

If there is something you don’t understand, please feel free to leave a comment below for further clarification.

Leave a Reply

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