You can use JavaScript’s filter() function to filter an object array based on attributes. The filter() function returns a new array containing all the elements that pass a given condition.
Syntax
array.filter(function(currentValue, index, array), thisValue)
Parameters
function(currentValue, index, array)
The function is required, and it is the function to be run for each element in the array.
Function arguments
Argument | Description |
---|---|
currentValue | Required. The value of the current element |
index | It is optional. The array index of the current item |
array | It is optional. The array object the current item belongs to |
thisValue
It is an optional parameter. A value is to be passed to the function to be used as its “this” value. If this parameter is empty, the value “undefined” will be given as its “this” value.
Return Value
The filter() function returns an array containing all the array elements that pass the test. If no items pass the test, it returns an empty array.
Example 1
let actors = [
{ name: 'Eleven', show: 'Stranger Things' },
{ name: 'Jonas', show: 'Dark' },
{ name: 'Mike', show: 'Stranger Things' },
{ name: 'Martha', show: 'Dark' },
{ name: 'Dustin', show: 'Stranger Things' },
]
STActors = actors.filter(actor => actor.show == 'Stranger Things');
console.log(STActors);
Output
[
{ name: 'Eleven', show: 'Stranger Things' },
{ name: 'Mike', show: 'Stranger Things' },
{ name: 'Dustin', show: 'Stranger Things' }
]
In the above code, we created an array of actors of objects, each containing two properties: name and show.
The actors array contains five objects representing actors from two TV shows, “Stranger Things” and “Dark”.
The filter() method is used on the actors’ array to create a new array STActors that contains only the objects with a show property equal to “Stranger Things”.
The filter() method takes a callback function that returns true or false for each array element.
In this case, the callback function checks if the show property of each element is equal to “Stranger Things”.
When the STActors array is logged to the console using console.log(STActors), the output will be an array containing only the objects representing actors from “Stranger Things”.
Example 2
// An array of objects
let arr = [
{ name: "Alice", age: 25 },
{ name: "Bob", age: 30 },
{ name: "Charlie", age: 35 }
];
// A condition to filter by age
let condition = (obj) => obj.age > 25;
// A new array with filtered elements
let newArr = arr.filter(condition);
// Output: [{name: "Bob", age: 30}, {name: "Charlie", age: 35}]
console.log(newArr);
Output
[ { name: 'Bob', age: 30 }, { name: 'Charlie', age: 35 } ]
That’s it.