To filter objects in JavaScript, you can use the filter()
method of an array. The filter()
method creates a new array with all elements that pass the test implemented by the provided function.
Here's an example of how to use the filter()
method with objects:
index.tsx247 chars11 lines
In this example, we have an array of objects representing people. We use the filter()
method to create a new array containing only those objects where the age
property is greater than 30.
The filter()
method takes a callback function as its argument. The function receives each element of the array (person
in this case) as its argument, and should return a boolean value – true
if the item should be included in the filtered array, and false
if not.
In the example above, we use an arrow function to define the callback function. The arrow function takes each person
object as its argument, and returns true
if the age
property of the object is greater than 30.
Note that the filter()
method does not modify the original array – it returns a new array containing the filtered items.
gistlibby LogSnag