Using Array.prototype.filter()
The Array.prototype.filter()
method returns a new array with all elements that satisfy the condition in the provided callback function. Therefore, you can use this method to filter an array of objects by a specific property's value, for example, in the following way:
// ES5+ const employees = [ { name: 'John', department: 'sales' }, { name: 'Wayne', department: 'marketing' }, { name: 'David', department: 'IT' }, { name: 'Bruce', department: 'marketing' }, ]; const filtered = employees.filter(function (emp) { return emp.department === 'marketing' }); console.log(filtered); /* [ {name: "Wayne", department: "marketing"}, {name: "Bruce", department: "marketing"} ] */
If a match is not found then the Array.prototype.filter()
method will return an empty array.
With ES6 arrow functions, you can shorten the syntax a bit, for example, like so:
// ES6+ // ... const filtered = employees.filter((emp) => emp.department === 'marketing'); // ...
In ES6+, you can also directly unpack the object in the callback function's argument, for example, like so:
// ES6+ // ... const filtered = employees.filter(({ department }) => department === 'marketing'); // ...
Using a Loop
If you're unable to support ES5, then you can simply use a loop (such as a for
loop) to iterate over the array of objects and populate a new array with elements you wish to keep. For example:
const employees = [ { name: 'John', department: 'sales' }, { name: 'Wayne', department: 'marketing' }, { name: 'David', department: 'IT' }, { name: 'Bruce', department: 'marketing' }, ]; const match = []; for (let i = 0; i < employees.length; i++) { if (employees[i].department === 'marketing') { match.push(employees[i]); } } console.log(match); /* [ {name: "Wayne", department: "marketing"}, {name: "Bruce", department: "marketing"} ] */
If a match is not found then "match
" will be an empty array.
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.