Three array methods cover most of what you will ever need to do with a list of records. filter keeps the items that match, find gives you the first one that matches, and reduce folds the whole list into a single value. This lesson shows you how each of them behaves on the same data, and where each one stops being the right tool.
The previous lesson in this module covered "forEach vs map vs for-of: Picking Loop Style", and the next lesson in this module is about "Sorting and Copying Arrays Without Surprises".
What does filter keep?
filter runs your test against every item and returns a new array that holds only the items for which the test returned a truthy value. The original array is left untouched, and the new array is always shorter than the original, never longer.
const orders = [
{ id: 'A-1', status: 'paid', total: 42 },
{ id: 'A-2', status: 'pending', total: 17 },
{ id: 'A-3', status: 'paid', total: 88 },
{ id: 'A-4', status: 'refunded', total: 5 },
];
const paid = orders.filter(function (order) {
return order.status === 'paid';
});
console.log(paid.length); // 2
const paidIds = [];
for (const order of paid) {
paidIds.push(order.id);
}
console.log(paidIds); // [ 'A-1', 'A-3' ]
Two details matter here. The callback receives one argument, which is the item itself, so the test reads like a plain question. Is this order paid? And because filter returns a new array, you can chain it. The code orders.filter(...).map(...) gives you the paid totals without touching the source list at all.
One more habit is worth forming. filter keeps whatever your test returns as truthy, and not only the value true. That is why items.filter(Boolean) is a tidy way to strip out null, undefined, empty strings, and zeros from a list. It is very handy after an API call that returns optional fields.
How do you get just the first matching item?
find applies the same kind of test, but it stops at the first hit and returns that item. If nothing matches, it returns undefined, which is why you should always check the result before you read properties off it.
const big = orders.find(function (order) {
return order.total > 50;
});
console.log(big.id); // A-3
const index = orders.findIndex(function (order) {
return order.total > 50;
});
console.log(index); // 2
const missing = orders.find(function (order) {
return order.total > 500;
});
console.log(missing); // undefined
findIndex gives you the position instead of the item, and findLast searches from the end. That is useful when the newest matching record is the one you want and your list is sorted by date. The undefined on the last line is the important one. Writing orders.find(...).id when nothing matched would throw a TypeError, so save the result in a variable first and check it before you use it.
How does reduce fold a list into one value?
reduce walks the array once, carrying a running value from item to item, and it returns the final value at the end. The callback takes two things. The first one is the value that you have built so far, and the second one is the current item. You must return the running value from the callback, or the next round receives undefined instead of it.
const basket = [
{ name: 'pen', price: 3, qty: 2 },
{ name: 'book', price: 12, qty: 1 },
];
const total = basket.reduce(function (sum, item) {
return sum + item.price * item.qty;
}, 0);
console.log(total); // 18
Read the code from the inside out. The running value starts at 0, each item adds its own line total, and the answer comes out as 18. The second argument, which is the 0, is the initial value, and it decides the shape of the running value for the whole run.
Why should you always pass an initial value?
Without one, reduce uses the first element of the array as the starting value. That works for addition, where the first element and the result share a type, and it quietly breaks for everything else.
console.log(['a', 'b', 'a'].reduce(function (a, b) {
return a + b;
})); // aba
try {
[].reduce(function (a, b) {
return a + b;
});
} catch (error) {
console.log(error.constructor.name + ': ' + error.message);
}
// TypeError: Reduce of empty array with no initial value
The empty array case is the loud one. The quiet one is building an object. With no initial value the running value starts as the first item rather than as an empty object, so your first assignment writes onto that item instead of onto a fresh accumulator. Passing {} or [] as the initial value removes the ambiguity and makes the callback correct for an empty input.
How do you group or count items with reduce?
Because the running value can be any type, reduce can build objects as well as numbers. This is how you group records by a field, or how you count the occurrences of each value, when no built-in method does exactly what you need.
const byStatus = orders.reduce(function (groups, order) {
if (!groups[order.status]) {
groups[order.status] = [];
}
groups[order.status].push(order.id);
return groups;
}, {});
console.log(byStatus);
// { paid: [ 'A-1', 'A-3' ], pending: [ 'A-2' ], refunded: [ 'A-4' ] }
const words = ['a', 'b', 'a'];
const counts = words.reduce(function (result, word) {
if (!result[word]) {
result[word] = 0;
}
result[word] = result[word] + 1;
return result;
}, {});
console.log(counts); // { a: 2, b: 1 }
The pattern to copy is the same in both cases. Read the current value for the key, create an empty value if there is not one yet, write the new value back, and return the running value. If you find yourself writing that loop often, then Object.groupBy and Map.groupBy now cover the grouping case directly, and the objects module covers them in full.
What about some and every?
Two siblings complete the set. some answers the question "does at least one item match?", and every answers the question "do all of the items match?". Both of them stop at the first decisive answer, so they are cheap on long lists.
const nums = [4, 8, 15, 16, 23, 42];
console.log(nums.some(function (n) {
return n > 40;
})); // true
console.log(nums.every(function (n) {
return n % 2 === 0;
})); // false
Which of the three should I use?
| Method | Returns | Use it when |
|---|---|---|
filter | A new array of matches | You want every matching record |
find | The first match, or undefined | You only need one record |
reduce | Whatever you define it to be | You are folding a list into one value |
some / every | A boolean | You only need a yes or no answer |
If you reach for reduce and find yourself writing a comparison inside it, then filter or find was probably clearer. If you reach for filter and immediately map the result, then it is worth asking whether one reduce would do the same job in a single pass.
Try it yourself: with the orders array above, write three separate helpers and print what each one returns. paidOrders(orders) should give the paid records. largestOrder(orders) should give the single record with the biggest total, so use reduce and make sure that it returns undefined for an empty array instead of throwing an error. totalByStatus(orders) should reduce the list into an object where each status maps to the sum of its totals, so the result is { paid: 130, pending: 17, refunded: 5 }.