DEV Community

Vicky Vasilopoulou
Vicky Vasilopoulou

Posted on

Reduce method with an input of a string or an object

The first example is just demonstrating how actually reduce method works behind the scenes and the next two examples how it could be used in a string or an object situation.

Example 1.

Calculate the total

In this example we are having an array of numbers and we want to return the total which is 6 in that case.

function Sum(numbers) {
 return numbers.reduce((acc, number) => {
   return acc + number
 }, 0)
}

Enter fullscreen mode Exit fullscreen mode

So what actually happens here.

iteration: 1     2        3
acc:       0     1        3
number:    1     2        3
return:    1     3        6
Enter fullscreen mode Exit fullscreen mode

So on the first iteration the accumulator is 0 as we set it up to 0.

The number on the first iteration is 1.

So the total of acc + number is 0 + 1 return: 1.

Now on the second iteration the accumulator is replacing 0 with 1. The number is 2 since we are on the second iteration and the return is 3.

On the third iteration the accumulator is 3 so our total in the end is 6.

Example 2.

Find the shortest word.

Let's say we have a function findShortestWord() which is getting as an input the following string as you see below on console.log. We want to return basically the shortest word which in that case is 'be'

console.log(findShortestWord("You can't always be correct."))
Enter fullscreen mode Exit fullscreen mode

There are many ways to solve this but my approach with reduce method would be:

function findShortestWord(string) {
    return string.split(' ')
        .reduce((short, total) => (
            short.length > total.length ?
                total :
                short
        ));
}
Enter fullscreen mode Exit fullscreen mode

Example 3.

Swapping key - value pair of an object

Let's say we have an object and we want to swap the key-values so it should return {Vicky: 'name', Vasilopoulou: 'lastName'}

console.log(swap({ name: 'Vicky', lastName: 'Vasilopoulou' }))

My approach with reduce would look like this:

function swap(obj) {
    return Object.keys(obj)
        .reduce((newObj, key) => {
            let value = obj[key];
            newObj[value] = key;
            return newObj;
        }, {});
}
Enter fullscreen mode Exit fullscreen mode

Top comments (8)

Collapse
 
devtalhaakbar profile image
Muhammad Talha Akbar • Edited

I have myself found .reduce to be very useful however, I think one must atleast put some time in naming the accumulator comprehensively so, it is self-evident what the list of items will be reduced to. Personally, in the first example, I would have named accumulator to be sum or total. In the second example, shortestWord. In the third (tricky) example, perhaps, reverseObject and, I would have defined reverseObject to be an object that has their keys / values swapped (as a comment).

However, like Ben said, this would definitely help JS developers to not shy away from .reduce and start using it in the projects!

Collapse
 
tqbit profile image
tq-bit

I always like to see elaborations about high order functions, especially .reduce looks, imo, quite counterintuitive at first. perhaps you could state what your function is attempting to do and enhance your example with an array of numbers as input.

reduce also works with other data types, like strings. that's quite handy to, for instance, dynamically create a string out of specific array elements

Collapse
 
vikirobles profile image
Vicky Vasilopoulou

I added another two examples. Thanks for your feedback. :)

Collapse
 
geminii profile image
Jimmy

Really nice explaination about the process of reduce iteration. Great work πŸ‘

Collapse
 
vikirobles profile image
Vicky Vasilopoulou

Thank you Jimmy!

Collapse
 
ben profile image
Ben Halpern

Love this type of post, definitely gonna help some JavaScript developers as they stumble on this.

Collapse
 
vikirobles profile image
Vicky Vasilopoulou

I actually came across on the object situation recently and thought would be great to share. Thank you Ben!

Collapse
 
mateja3m profile image
Milan Matejic

Very interesting explanation. Reduce method is one of the most important methods working with arrays.