Algorithm Rebuild Using Reduce & Accumulator
Cleaner code all contained in one method
In my last blog post (Introduction to Algorithms) I built a function that counted how many of a single item was present in an array. I had to set a counter variable outside of the for each statement in order to count each smiley face in an array. I mentioned in that post that there’s usually more than one way to write an algorithm to carry out the same task. In this blog post, I’ll build a different algorithm to carry out the same task of counting smiley faces in an array. However, this algorithm will contain all of the functionality inside of the method, instead of pre-setting a counter outside of an iterator.
First, a quick reminder of what I initially built to count smiley faces:
To distinguish the current function I’m about to build from my last, I’ll call it accumSmileyFaces since I’ll use an accumulator instead of a counter. I’ll use the arr parameter again to pass in an array.
function accumSmileyFaces( arr ) { }
Inside of my function, this time I’ll use the reduce method instead of the for each iterator. Reduce can iterate over each item in my array and return a single number. Since I want a single total number of smiley faces in an array, reduce is perfect for this task.The reduce method takes a call back function with two parameters, an accumulator and the current item (face) iteration. I use an arrow function to express this and I also set my accumulator to start at 0.
Inside of the call back function, I’ll use a ternary statement to check for smiley faces then count them with my accumulator.
Since I’m using a function inside of a function, I need two returns to get my total count of smiley faces
Let’s try it on the original faces array.
=>> 5
It returned a count of 5 just like the countSmileyFaces function did. How about the other arrays?
accumSmileyFaces([ “😁”, “😡”, “😡”, “😁”])
=>> 2
accumSmileyFaces([ “😡”, “😡”, “😁”, “😡”, “😡”])
=>> 1
accumSmileyFaces([ “😁”, “😁”, “😁”, “😡”, “😡”, “😁”])
=>> 4
It works! The accumSmileyFaces function works just like the countSmileyFaces function but accumSmileyFaces is cleaner because all of the code is contained inside of the reduce method instead of pre-setting a counter outside of the iteration. I’ve included the two functions below for comparison.
countSmileyFaces function [uses a counter]
accumSmileyFacces function [uses an accumulator]