Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 5.5 — reduce
JavaScript · Example 2 of 3 ES2024+

Count and group

?? is ES2020, ??= is ES2021 and Object.groupBy is ES2024. Object.groupBy keeps the whole objects in each group; the hand-written reducer kept only names.

reduce walks through an array carrying one running value (the accumulator) and combines each item into it, turning a whole list into a single result such as a total, a count, a maximum or a grouped object; always give it a starting value.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Use reduce to find the total price of [{ name: "Pen", price: 20 }, { name: "Bag", price: 900 }].

02

Use reduce to turn [["a", 1], ["b", 2]] into { a: 1, b: 2 }.

03

Group [1, 2, 3, 4, 5] into { odd: [...], even: [...] } with Object.groupBy.

Explain it without notes

01

Explain how reduce works step by step for a sum.

02

What happens when you call reduce without an initial value?

03

How would you count how many times each word appears in an array?

04

When is a for...of loop better than reduce?

Count and group ES2024+

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

{ tea: 3, coffee: 2, juice: 1 }
{ Pune: [ 'Asha', 'Meera' ], Delhi: [ 'Ravi' ] }
[ 'Pune', 'Delhi' ] 2