How to Filter Array of Objects in JavaScript
This article will teach you how to filter elements in an array using the JavaScript filter()
function.
Filter Array of Objects in JavaScript
When working with an array, one of the most typical jobs is to build a new collection that includes a subset of the original array’s members. Assume you have a variety of student objects, each of which has two properties: sports
and subjects
.
const students = [
{sports: ['cricket', 'football'], subjects: 'Science'},
{sports: ['Badminton', 'Hockey'], subjects: 'Math'},
{sports: ['Chess', 'cricket'], subjects: 'Computer Science'},
{sports: ['Judo', 'football'], subjects: 'Social Science'},
];
To find the students whose favourite sports is cricket, you have to filter the sports that includes the cricket
like this:
const Cricket = students.filter((e) => e.sports.includes('cricket'));
console.log(Cricket);
Output:
[{
name: "Johnny",
sports: ["cricket", "football"]
}, {
name: "Dev",
sports: ["Chess", "cricket"]
}]
In this example, we used the students
array object’s filter()
method and passed a program that tests each member. Within the function, we determined if the sports of each student in the array correspond to cricket
.
If this is the case, the function returns true
; otherwise, it returns false
. The filter()
method contains just those elements in the return array that pass the callback function’s condition.
Shiv is a self-driven and passionate Machine learning Learner who is innovative in application design, development, testing, and deployment and provides program requirements into sustainable advanced technical solutions through JavaScript, Python, and other programs for continuous improvement of AI technologies.
LinkedInRelated Article - JavaScript Array
- How to Check if Array Contains Value in JavaScript
- How to Create Array of Specific Length in JavaScript
- How to Convert Array to String in JavaScript
- How to Remove First Element From an Array in JavaScript
- How to Search Objects From an Array in JavaScript
- How to Convert Arguments to an Array in JavaScript