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
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
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’
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;
object[key]++;
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 [...new Set(mostFrequentElements)];
}
findMostFrequentElements([1,2,2,3,4,5,5]) // returns [2,5]
Thanks for reading and I hope this introduced new ideas around using reduce.
Top comments (0)