Arrays · Lesson 21 of 45
reduce and sorting
Fold a list into one value, and sort correctly.
9 minutes3 games
reduce walks through the items and folds them into one value: a total, a maximum, or an object. It takes a callback (acc, item) where acc is the result so far, plus a starting value.
Step by step1 / 5
- ▶const nums = [5, 10, 20]
- 2const total = nums.reduce((acc, n) => acc + n, 0)
- 3console.log(total)
Variables
| nums | [5, 10, 20] |
Output
…
JavaScript
const cart = [
{ item: "Pen", price: 15, qty: 2 },
{ item: "Mug", price: 90, qty: 1 },
]
const total = cart.reduce((sum, row) => sum + row.price * row.qty, 0)
console.log("Total:", total)
const words = ["js", "css", "js", "html", "js"]
const counts = words.reduce((acc, w) => {
acc[w] = (acc[w] ?? 0) + 1
return acc
}, {})
console.log(counts)Sorting with sort
Plain sort() sorts as text, so [10, 9, 1] becomes [1, 10, 9]! For numbers pass a compare function: (a, b) => a - b ascending, (a, b) => b - a descending. Careful: sort changes the original array.
JavaScript
console.log([10, 9, 1].sort()) // [1, 10, 9]
console.log([10, 9, 1].sort((a, b) => a - b)) // [1, 9, 10]
const players = [{ name: "Ali", score: 70 }, { name: "Sara", score: 95 }, { name: "Omar", score: 82 }]
const ranked = [...players].sort((a, b) => b.score - a.score)
console.log(ranked.map((p) => p.name))
console.log(["mango", "apple", "kiwi"].toSorted())What's the output?
console.log([1, 2, 3, 4].reduce((a, n) => a * n, 1))
What will this code print?
Complete the code
Sort the numbers from largest to smallest.
nums.sort((a, b) => - )
Exercise
Print the largest number using reduce (88).
Expected output: 88
JavaScript
const scores = [40, 88, 61, 75]
Learn more from
Played 0 of 3 games
Sign in to save your progress and earn XP.