Menu

Post image 1
Post image 2
1 / 2
0

How to Use reduce() for Data Grouping and Aggregation in JavaScript

DEV Community·137Foundry·30 days ago
#kt8d5BW6
Reading 0:00
15s threshold

reduce() is the most capable and most underused JavaScript array method. Most developers know it computes sums. Fewer realize it handles grouping, indexing, deduplication, and building any data structure from an array. This guide walks through the practical applications step by step. Step 1: Understand the Accumulator reduce() takes a callback and an optional initial value. The callback receives the accumulator (the running result) and the current element. Whatever the callback returns becomes the new accumulator. array . reduce (( accumulator , current ) => { // return the new accumulator }, initialValue ); Enter fullscreen mode Exit fullscreen mode The initial value determines what kind of result you get. Start with 0 to sum numbers. Start with {} to build an object. Start with [] to build an array. The type of the initial value is the type of the final result. Step 2: Sum and Average The basic case: summing an array of numbers. const prices = [ 12.99 , 5.50 , 22.00 , 8.75 ]; const total = prices .…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.

Read More