DEV Community


Posted on

3 ways to use JS reduce

In Javascript reduce is a method that loops through the elements of an array and returns a single value. The single value can be a range of different things such as returning a number, string, or object, which will be discussed below.

Learning about reduce

MDN link on reduce

Mathematical Reduce

Usually, reduce is used to return a mathematical result:

function sumFunc(arrayOfNumbers) {
  let sum = arrayOfNumbers.reduce((total, number) => total + number, 0);

  return sum; 

sumFunc([1,2,3]) // returns 6
Enter fullscreen mode Exit fullscreen mode

String Reduce

However, reduce can do more than just return a single numerical value. It can also return a string:

function reverseWordFunc(word) {
    // create array of letters basically word.split(‘’) 
    let letterArray = [...word];

    let reverse = letterArray.reduce((reversedWord, letter) => letter + reversedWord, '');

    return reverse; 

reverseWordFunc('hello') // returns ‘olleh’
Enter fullscreen mode Exit fullscreen mode

NOTE: This version of using reduce is concatenating the accumulating string to the letter, which is why we get the word in reverse. However, by switching the order of the parameters we can get the word in order i.e. letterArray.reduce((reversedWord, letter) => reverseWord, letter, ‘’)

Object Reduce

And it can even be used to return an object or a “hash table”:

function findMostFrequentElements(array) {
  let hashtable = array.reduce((object, key) => {
    // initialize property  or use existing value 
    object[key] = object[key] || 0;
    return object; 
  }, {}); // returns {1: 1, 2: 2, 3: 1, 4: 1, 5: 2}

    // get the frequency each element occurs 
    let getFreqency = Object.values(hashtable);
    // get the max of occurrences for an element
    let max = Math.max(...getFreqency);
    // filter to see which elements in the hash table appear the most
    let mostFrequentElements = array.filter(key => hashtable[key] === max); // returns [2,2,5,5]

    // remove any repeating elements 
    return [ Set(mostFrequentElements)];

findMostFrequentElements([1,2,2,3,4,5,5]) // returns [2,5]
Enter fullscreen mode Exit fullscreen mode

Thanks for reading and I hope this introduced new ideas around using reduce.

Top comments (0)