4 Use Cases for reduce() in JavaScript

4 Use Cases for reduce() in JavaScript

Real-world use case of the reduce() method

Hey guys, In this article, we would continue our discussion on the reduce method but we are going to focus more on the use cases. As this is the second part of a two-series article, it is important that you've read the first part of the reduce method series titled Everything you need to know about the reduce() method. . It is the foundation from which this article is built on and the core essential basics of the reduce method have been thoroughly covered in that article. Let’s dive right into it.

Use Cases of the reduce method

1. Summing all the values of an array

This is one of the easiest use cases of the JavaScript reduce method because it is simply used to get the sum total of a list of numbers. Let’s see an example

const numbers = [2, 10, 12, 4, 6];

const totalNumber = numbers.reduce((total, number) => {
  return total + number;
}, 0);

console.log(totalNumber); // output : 34

If you do not understand what is going on with the example we just did. You have to go back to the first part of the article because it is very well explained there.

2. Grouping objects by a property

Based on the properties of an object, we can group the object array into several groups using the reduce() method. Let’s see an example 👇🏽

const students = [
  { name: 'lawrence', age: 32 },
  { name: 'james', age: 22 },
  { name: 'loveth', age: 16 },
  { name: 'james', age: 42 },
];

const result = students.reduce((groupedStudents, person) => {
  const name = person.name;
  if (groupedStudents[name] == null) {
    groupedStudents[name] = [];
  }

  groupedStudents[name].push(person);
  return groupedStudents;
}, {});

console.log(result);

Here, students object array has five objects, and each object has nameand age properties. After that, we then get the name of each person and we also check if we have a value for that name. If we don’t have a value for the name, then we will have to default the groupedStudents of thatname into an empty array. and the reduce()is used to do just that.

After that, the empty object {} is then assigned to the groupedStudents, then the push() method adds person object to the empty {} object arrays after checking the condition.

Here is the output 👇🏽

Hopefully, this explanation makes sense, If you still do not understand it, you can definitely console log some things out for yourself. I will leave the GitHub link to the code at the end of the article.

3. Flatten a List of Arrays

Flattening an array simply means breaking or transforming nested arrays into a single array. And the reduce() method can be used to accomplish that task. Let’s see an example 👇🏽

const twoDimArry = [
  ['james', 'mark', 'becky', 'great'],
  ['adam', 'ben', 'bright'],
  ['sarah', 'lisa'],
];

const flattenedArry = twoDimArry.reduce((accumulator, currentArray) =>
  accumulator.concat(currentArray)
);
console.log(flattenedArry); 

// output: ['james', 'mark', 'becky', 'great', 'adam', 'ben', 'bright', 'sarah', 'lisa']

In the code above, the twoDimArray array is transformed into flattendedArry array.

The first ['james', 'mark', 'becky', 'great'] array is assigned to the accumulator and then each rest of the elements of the twoDimArray array is concatenated (which is the concat method)to the accumulator.

If you are wondering what is concat method?

The concat() method is used to merge two or more arrays. This method does not change the existing arrays but instead returns a new array( From mdn docs ).

4. Remove duplicates in an array

The reduce() method can also be used to remove duplicate values in an array. Let’s see an example 👇🏽

const duplicatedsArr = [
  'rice',
  'beans',
  'plantain',
  'yam',
  'rice',
  'egg',
  'beans',
  'meat',
  'beef',
  'rice',
];

const removeDuplicatedArr = duplicatedsArr.reduce((acc, item) => {
  if (!acc.includes(item)) {
    acc.push(item);
  }
  return acc;
}, []);

console.log(removeDuplicatedArr);

//output:
['rice', 'beans', 'plantain', 'yam', 'egg', 'meat', 'beef']

In the above code example, duplicates in the duplicatedArr array are removed. First, an empty array is assigned to the acc as initial value. accu.includes() checks whether each element of the duplicatedArr array is already available in the accumulator. If the item is not available in the accumulator, it is added using the push().

Conclusion

That’s all guys, hopefully, you understand the use cases we covered in this article. And one thing to note is that there are more use cases other than the ones we talked about. But these are the ones that are mostly used. Like I said in the middle of the article here is a GitHub link to all the examples we talked about and I also added some more examples to it too 👇🏽

https://github.com/dev-lawrence/Array-methods

Have a nice weekend..See you next week 😀