javascript

Filter an Array using object key value in Javascript

If you have an array of objects and you want to filter the array by a key value, you can use the filter() method in JavaScript. The filter() method creates a new array with all the elements that pass the test implemented by the callback() function.

Filter an Array using object key value in Javascript

To filter an array that contains multiple objects as its items and each object has some key-value pairs. To filter the array:

  1. Define the array of objects.
  2. Apply filter() function on the array and in the callback function apply some condition.
  3. If the condition is true return the element to a new variable.
  4. Print the variable that contains filtered objects.

# Method 1: Using filter() function

Now let's filter the array using the filter() function. We will be using the ES6 arrow function to pass as a callback. If you are using ES5 then you can use the next example.

const students = [
    { id: 1, name: "John", marks: 91 },
    { id: 2, name: "Sumesh", marks: 89 },
    { id: 3, name: "Rick", marks: 78 },
    { id: 3, name: "Monty", marks: 93 }
];

const filtered_students = students.filter(item => item.marks > 90);

console.log(filtered_students);

ES5 code to filter array

const filtered_students = students.filter(function(item) {
    return item.marks > 90
});

Output

[
   {"id":1,"name":"John","marks":91},
   {"id":3,"name":"Monty","marks":93}
]

Live Demo

The code above is using the filter() method to create a new array with all the elements that have a "marks" property greater than 90. The result is an array with two objects inside of it.

In the above code example, we are using the filter() function to filter the array of objects by value. There are more methods that can be used for the same purpose. We will explain them one by one here.


Was this helpful?