find and filter arrays in JavaScript and Node.js
If you need to search or filter an array of objects, then this article will show you the most common ways of doing so using JavaScript’s built-in functions.
Find Vs Filter
Just to be clear finding
and filtering
produce different results.
find
will return a single value: the first matching value found.filter
will return multiple values: all matching values
Example data
If you want to follow along, this is the example data I will be using.
data.json
[
{
"id": 1,
"name": "Joe Bloggs"
},
{
"id": 2,
"name": "Jane Doe"
},
{
"id": 3,
"name": "John Doe",
"address": {
"street": "21 Lime Street",
"city": "London"
}
}
]
Find
Let’s start with finding data.
Finding one record by a fields absolute value
let users = require('./data.json');
let findId1user = users.find(user => user.id == 1)
console.log(findId1user)
result
{ id: 1, name: 'Joe Bloggs' }
The above example correctly finds the object with id: 1
If we try to find a value that could relate to more than one record, we will only get the first matching record.
let users = require('./data.json');
let findDoeUsers = users.find((user) => user.name.includes('Doe'));
console.log(findDoeUsers);
result
{ id: 2, name: 'Jane Doe' }
The above example shows that only Jane Doe
is returned, even though John Doe
also matches.
If we need to return all matching records, we need to use filters, which we will look at further down.
Finding a value where the field does not exist in all records.
The following example will give an error
let users = require('./data.json');
let findCityLondon = users.find(user => {
return user.address.city.includes("London")
})
console.log(findCityLondon)
result
TypeError: Cannot read property 'city' of undefined
The reason for the above error is that only one of the three records has an address element.
We can overcome this error with a try/catch
block
let users = require('./data.json');
let findCityLondon = users.find((user) => {
try {
return user.address.city.includes('London');
} catch {
return false
}
});
console.log(findCityLondon);
result
{
id: 3,
name: 'John Doe',
address: { street: '21 Lime Street', city: 'London' }
}
The try/catch
catches the error and returns false, which simply means the record will not be included in the result.
Find summary
Although you can do more complex searches with tools such as lodash , the built-in find will be enough for 90% of the time.
Filter
As mentioned above, filter
will return multiple records that match the filter criteria.
In the example above where we used find
to return records with a name field containing Doe
we only got one record returned, the first record that matched.
In the following example, I use filter
with the same criteria.
let users = require('./data.json');
let filterDoe = users.filter(user => user.name.includes("Doe"))
console.log(filterDoe)
result
[
{ id: 2, name: 'Jane Doe' },
{
id: 3,
name: 'John Doe',
address: { street: '21 Lime Street', city: 'London' }
}
]
As you can see, filter
returns an array and it contains both records with the name field that contains the Doe
Filter Summary
Just as I summarised the find
section above, tools such as lodash
can do far more, but in most cases, JavaScript’s built-in filter
method will be all you need.
Summary
The methods listed above are synchronous, that is they will block until the result is returned. There are other