Find an object in an array by property in JavaScript
Beginner · 3 min read
Real data usually comes as a list of objects: users, orders, products, buses. A common job is "find the bus with plate ABJ-772-KM" or "find the order with id 42". In this tutorial you will look up a record by one of its fields, and handle the case where it isn't there without crashing the code that called you.
You will use three array methods, find, findIndex and filter, and then a Map for when you need to look things up many times. You need to know arrays, objects and arrow functions. Each method is explained as we go.
The data
Each bus is an object with a plate, a route and a seat count:
const buses = [
{ plate: 'LAG-441-XA', route: 'Lagos - Abuja', seats: 14 },
{ plate: 'ABJ-772-KM', route: 'Lagos - Kano', seats: 30 },
{ plate: 'ENU-318-PH', route: 'Lagos - Abuja', seats: 7 },
];
console.log(buses[1].plate); // 'ABJ-772-KM'
You can't use indexOf here. It compares whole items, and you want to match on one field inside each item.
Methods that take a rule
find takes a function and calls it on each item in turn. The function returns true for a match. find hands back the first item where that happens:
const nums = [4, 9, 12, 15];
console.log(nums.find((n) => n > 10)); // 12
console.log(nums.find((n) => n > 99)); // undefined
When nothing matches, find returns undefined.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
4 Search a list of records by field
easyFind a record in a list by one of its fields. Return the record, and handle "not found" without crashing the caller.
Stuck? Three hints, smallest first
- 1.
findreturns the item orundefined;findIndexreturns the position or-1. - 2. For repeated lookups on the same data, build a
Maponce instead of searching every time. - 3. A linear
findis O(n) per lookup; a Map is O(1) after an O(n) setup.
Step 1: find by plate
The rule compares each bus's plate with the one we want:
const buses = [
{ plate: 'LAG-441-XA', route: 'Lagos - Abuja', seats: 14 },
{ plate: 'ABJ-772-KM', route: 'Lagos - Kano', seats: 30 },
{ plate: 'ENU-318-PH', route: 'Lagos - Abuja', seats: 7 },
];
const found = buses.find((b) => b.plate === 'ABJ-772-KM');
console.log(found.seats); // 30
Step 2: the crash on a miss
Now look for a plate that isn't there, and read a field from the result:
const buses = [{ plate: 'LAG-441-XA', seats: 14 }];
const missing = buses.find((b) => b.plate === 'KAN-905-BD');
console.log(missing); // undefined
try {
console.log(missing.seats);
} catch (e) {
console.log(e.constructor.name); // 'TypeError'
}
Reading a field from undefined throws a TypeError. The caller must check the result before using it.
Step 3: return null for "not found"
The answer returns null on a miss. ?? null means "if the left side is null or undefined, use null". Why bother? undefined is also what you get from a typo like bus.seat, so a clear null says "this record genuinely isn't there":
const buses = [
{ plate: 'LAG-441-XA', route: 'Lagos - Abuja', seats: 14 },
{ plate: 'ABJ-772-KM', route: 'Lagos - Kano', seats: 30 },
];
const findByPlate = (plate) => buses.find((b) => b.plate === plate) ?? null;
console.log(findByPlate('ABJ-772-KM').route); // 'Lagos - Kano'
console.log(findByPlate('KAN-905-BD')); // null
Step 4: every match, or the position
filter uses the same kind of rule but returns all matches, as a new array. It returns an empty array, never null, when nothing matches. findIndex returns the position instead of the item, or -1:
const buses = [
{ plate: 'LAG-441-XA', route: 'Lagos - Abuja', seats: 14 },
{ plate: 'ABJ-772-KM', route: 'Lagos - Kano', seats: 30 },
{ plate: 'ENU-318-PH', route: 'Lagos - Abuja', seats: 7 },
];
const onRoute = (route) => buses.filter((b) => b.route === route);
console.log(onRoute('Lagos - Abuja').map((b) => b.plate)); // [ 'LAG-441-XA', 'ENU-318-PH' ]
console.log(onRoute('Lagos - Jos')); // []
console.log(buses.findIndex((b) => b.plate === 'ENU-318-PH')); // 2
Step 5: many lookups with a Map
find checks items one by one, every time you call it. If you look up plates thousands of times, build a Map once. A Map stores key and value pairs, and get(key) jumps straight to the value without scanning:
const buses = [
{ plate: 'LAG-441-XA', route: 'Lagos - Abuja', seats: 14 },
{ plate: 'ABJ-772-KM', route: 'Lagos - Kano', seats: 30 },
];
const index = new Map(buses.map((b) => [b.plate, b]));
const lookup = (plate) => index.get(plate) ?? null;
console.log(lookup('ABJ-772-KM').seats); // 30
console.log(lookup('KAN-905-BD')); // null
buses.map((b) => [b.plate, b]) makes a list of [key, value] pairs, which is what new Map expects. Building it costs one pass over the list. After that, each lookup takes about the same time however long the list is.
Step 6: you get the real object back
find doesn't copy. It returns the very object inside the array:
const buses = [{ plate: 'LAG-441-XA', seats: 14 }];
const bus = buses.find((b) => b.plate === 'LAG-441-XA');
bus.seats = 0;
console.log(buses[0].seats); // 0
Changing the result changes the list. Copy it first with { ...bus } if you don't want that.
The full solution
The panel has all four lookups on the same list of buses. Press Run to see a hit, a miss, and both buses on the Abuja route.
const buses = [
{ plate: 'LAG-441-XA', route: 'Lagos - Abuja', seats: 14 },
{ plate: 'ABJ-772-KM', route: 'Lagos - Kano', seats: 30 },
{ plate: 'ENU-318-PH', route: 'Lagos - Abuja', seats: 7 },
];
// One-off lookup.
const findByPlate = (plate) => buses.find((b) => b.plate === plate) ?? null;
// Repeated lookups: pay the O(n) once, then every lookup is O(1).
const index = new Map(buses.map((b) => [b.plate, b]));
const lookup = (plate) => index.get(plate) ?? null;
// All matches, not just the first.
const onRoute = (route) => buses.filter((b) => b.route === route);
console.log('found :', findByPlate('ABJ-772-KM'));
console.log('missing :', findByPlate('KAN-905-BD'));
console.log('two on the Abuja run:', onRoute('Lagos - Abuja').map((b) => b.plate));
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a record is found', findByPlate('ABJ-772-KM').seats, 30);
test('missing returns null, not undefined', findByPlate('KAN-905-BD'), null);
test('the map agrees', lookup('ABJ-772-KM').seats, 30);
test('and on a miss', lookup('KAN-905-BD'), null);
test('filter finds every match', onRoute('Lagos - Abuja').length, 2);
test('an unknown route gives an empty list', onRoute('Lagos - Jos'), []);
test('find returns the object itself, not a copy', findByPlate('LAG-441-XA') === buses[0], true);
test('findIndex is the positional twin', buses.findIndex((b) => b.plate === 'ENU-318-PH'), 2);
The ?? null is deliberate: find returns undefined on a miss, and undefined is also what you get from a typo in a property name, so normalising to null makes "genuinely absent" distinguishable. The last assertion is worth noticing too — find hands back the actual object, so mutating the result mutates the list.
Common mistakes
- Using a field of the result without checking it. A miss gives
undefined(ornullhere), and reading.seatsfrom it throws. - Using
findwhen you need every match. It stops at the first. Usefilter. - Expecting
filterto returnnullon a miss. It returns[], so check.length === 0.
Try it yourself
- Write
findBy(list, field, value)that works for any field, such asfindBy(buses, 'route', 'Lagos - Kano'). - Find the bus with the most seats using
reduce. - Build a
Mapfrom route to a list of plates, so'Lagos - Abuja'gives both plates.