Reduce Function with 3 examples

If you are a javascript developer you have probably heard of reduce functions. If you don't know what it is and why we need it. Don't worry I will sort this for you with 3 examples.

#1. Calculating total reveneu

Let's say you have a revenue of different products [100, 240, 1400, 400, 50] and you are ready to calculate total revenue. In order to do that you kinda need to go all over the values and add them to a variable called totalReveneu. That’s how we do it in a for loop. But using a reduce function you can make your job a lot easier.

const revenue = [100,240,1400,400,50]

const sum = revenue.reduce((accumulator, num) => accumulator + num, 0)

console.log(sum) // Output: 2190

As you can see, the code is way smaller compared to a traditional for-loop. The .reduce() function takes the first input as a callback function with two arguments and initializer number 0.

  • accumulator is whatever the previous operation value is
  • number from the current index. Similar to value[index] in for loop.
  • The last parameter 0 is the initial value for the accumulator. Similar to how you initiate totalReveneu as 0 before the for loop begins.

Here is what the opperation looks like

Okay that's easy right? Let's pick another example when you need to group an array based on a specific conditions. I pick age for simplicty here.

#2. Grouping Data

const people = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 25 },
  { name: 'David', age: 30 },
  { name: 'Eve', age: 35 },
];


const groupedAge = people.reduce((accumulator, person) => {

	 // Determine the age group (e.g., 20s, 30s, etc.)
  	const ageGroup = Math.floor(person.age / 10) * 10} + 's';
  	
  	// If the age group doesn't exist in the accumulator, create it. 
    // This prevents throwing an error when we try push in to it. 
	if (!acc[ageGroup]) {
		acc[ageGroup] = [];
	}
	
	 // Add the person to the appropriate age group
  	acc[ageGroup].push(person);
  
  	return acc;

}, {})

console.log(groupedByAge);

Now we take a bit further and expalnd the callback function. We determine ageGroup (20s, 30s) and create that group if it doesn't exist and push it to the appropriate group. Remmember we always need the updated version of `acc` so at the end of our callback function we have `return acc;`

Note: we are not initializing accumulator as `0` this time instead as an empty object {} . Since we are returning and object and altering it in every loop.

The output looks something like

{
  '20s': [ { name: 'Alice', age: 25 }, { name: 'Charlie', age: 25 } ],
  '30s': [
    { name: 'Bob', age: 30 },
    { name: 'David', age: 30 },
    { name: 'Eve', age: 35 }
  ]
}

#3. Summarizing Sales Data by Category

IdProductQuantityPriceCategory
1Phone2500Electronics
2TV11000Electronics
3T-Shirt520Clothing
4Jeans240Clothing
5Laptop11500Electronics
6Tablet3300Electronics
7Jacket1120Clothing
8Smartwatch4200Electronics
9Sneakers280Clothing
10Gaming Console1400Electronics
11Socks105Clothing
12Headphones3150Electronics
13Dress260Clothing
14Camera1800Electronics
15Hat325Clothing
16Monitor2350Electronics
17Sweater450Clothing
18Mouse530Electronics
19Keyboard360Electronics
20Scarf615Clothing