To filter an array of objects by key in JavaScript, you can use the Array.filter()
method. The filter()
method takes in a callback function as a parameter and returns a new array that contains only those records which satisfy the given condition.
Let’s say we have an array of students, which holds the name and marks of each student.
const students = [ { name: 'John', marks: 89 }, { name: 'Robert', marks: 74 }, { name: 'Smith', marks: 79 }, { name: 'George', marks: 85 }, { name: 'Oliver', marks: 78 }, ];
We want to filter out only those students from the students
array whose marks are greater than 80.
To filter out these records from the students
array, we can apply the filter()
method on it. The filter()
method will implicitly pass each student to the callback function, where we can specify the condition on which we want to filter the records.
The following example filters only those students whose marks are greater than 80:
const students = [ { name: 'John', marks: 89 }, { name: 'Robert', marks: 74 }, { name: 'Smith', marks: 79 }, { name: 'George', marks: 85 }, { name: 'Oliver', marks: 78 }, ]; // Filter students having marks greater than 80 const filterStudents = students.filter(student=>student.marks>80); console.log(filterStudents); // Output: // [ {name: "John", marks: 89}, {name: "George", marks: 85} ]
You can also filter out records based on multiple keys.
The following example filters those students whose age is more than 25 and also the marks obtained are greater than 80.
const students = [ { name: 'John', age: 24, marks: 89 }, { name: 'Robert', age: 26, marks: 92 }, { name: 'Smith', age: 21, marks: 79 }, { name: 'George', age: 27, marks: 85 }, { name: 'Oliver', age: 22, marks: 78 }, ]; // Filter students having marks greater than 80 and age>25 const filterStudents = students.filter(student=>student.marks>80 && student.age>25); console.log(filterStudents); // Output: // [ {name: "Robert", age: 26, marks: 92}, {name: "George", age: 27, marks: 85} ]
If no record satisfies the condition specified inside the callback function, the filter()
method returns an empty array.
Example:
const students = [ { name: 'John', marks: 89 }, { name: 'Robert', marks: 74 }, { name: 'Smith', marks: 79 }, { name: 'George', marks: 85 }, { name: 'Oliver', marks: 78 }, ]; // Filter students having marks more than 90 const filterStudents = students.filter(student=>student.marks>90); console.log(filterStudents); // Output: []