find and filter arrays in JavaScript and Node.js

Find Vs Filter

  • find will return a single value: the first matching value found.
  • filter will return multiple values: all matching values

Example data

[
{
"id": 1,
"name": "Joe Bloggs"
},
{
"id": 2,
"name": "Jane Doe"
},
{
"id": 3,
"name": "John Doe",
"address": {
"street": "21 Lime Street",
"city": "London"
}
}
]

Find

Finding one record by a fields absolute value

let users = require('./data.json');

let findId1user = users.find(user => user.id == 1)
console.log(findId1user)
{ id: 1, name: 'Joe Bloggs' }

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);
{ id: 2, name: 'Jane Doe' }

Finding a value where the field does not exist in all records.

let users = require('./data.json');

let findCityLondon = users.find(user => {
return user.address.city.includes("London")
})
console.log(findCityLondon)
TypeError: Cannot read property 'city' of undefined
let users = require('./data.json');

let findCityLondon = users.find((user) => {
try {
return user.address.city.includes('London');
} catch {
return false
}
});
console.log(findCityLondon);
{
id: 3,
name: 'John Doe',
address: { street: '21 Lime Street', city: 'London' }
}

Find summary

Filter

let users = require('./data.json');

let filterDoe = users.filter(user => user.name.includes("Doe"))
console.log(filterDoe)
[
{ id: 2, name: 'Jane Doe' },
{
id: 3,
name: 'John Doe',
address: { street: '21 Lime Street', city: 'London' }
}
]

Filter Summary

Summary

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store