Learn JavaScript · lesson 34 of 60 · about 8 minutes
reduce(), find() and sort()
Find the post for a tag, rank the top posts and count the tags: find, sort a copy, and reduce.
What you'll learn
- Total with reduce()
- Find an item with find()
- Sort with a compare function
Tags and top posts
Each post has tags, and a visitor who clicks one wants the first post with it: find stops at the first match and gives back that post, or undefined. Sam also wants the three most-liked posts at the top of the page, so the posts are sorted by likes. sort changes the array it's called on, and the posts must stay oldest first for the rest of the page, so a copy is sorted instead. reduce counts the tags in one line.
reduce and find
reduce((acc, item) => ..., start)walks the array carrying an accumulator, the same pattern as a running totalfind(fn)returns the first item where fn is true, or undefinedsome(fn)andevery(fn)answer "any?" and "all?" with true or false
Totals and lookups
const cart = [
{ item: "hat", price: 50 },
{ item: "scarf", price: 30 },
{ item: "boots", price: 90 },
];
const total = cart.reduce((sum, line) => sum + line.price, 0);
const scarf = cart.find((line) => line.item === "scarf");
console.log(total);
console.log(scarf.price);
console.log(cart.some((l) => l.price > 80), cart.every((l) => l.price > 40));Output
170
30
true falseSorting numbers properly
sort() with no function sorts as text, so 10 comes before 9. Pass (a, b) => a - b for low to high, or b - a for high to low. sort changes the original array.
Text sort versus number sort
console.log([10, 9, 1, 100].sort().join(" "));
console.log([10, 9, 1, 100].sort((a, b) => a - b).join(" "));
console.log(["kiwi", "apple", "fig"].sort().join(" "));Output
1 10 100 9
1 9 10 100
apple fig kiwiTip
Give reduce a start value. Without one it uses the first item, and on an empty array it throws a TypeError.
Now try it yourself
This lesson is free in Codiqo, with 11 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.