The Startup
Published in

The Startup

Ways to Use the Reduce Method in Javascript

Photo by Emile Perron on Unsplash
let arr = [1,2,3,4,4,5]; //sourceArraylet sum = 0; //initialValue, used to start accumulationfor(let elem of arr){
sum = sum + elem;
//accumulator + currentIndex (elem of array)
//0 + 1 - initial value plus elem
//1 + 2 - sum of previous iteration plus next elem in array
//3 + 3
//6 + 4
//10 + 4
//14 + 5
//19 - returns after last elem
}
console.log(sum) //prints 19
let sum = (arr) => {
return arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0 //optional initialValue, defaults 0)
//accumulator + currentValue (each elem of array)
//0 + 1 - initial value plus elem
//1 + 2 - sum of previous round plus next elem in array
//3 + 3
//6 + 4
//10 + 4
//14 + 5
//19 - returns after last elem
}console.log(sum([1,2,3,4,4,5])) //prints 19
let str = 'banana';
let obj = {};
for (let char of str){
obj[char] ? obj[char] += 1 : obj[char] = 1
//if the key exists, increment its value by one; otherwise initiate key with a value of 1
}
console.log(obj) // { b: 1, a: 3, n: 2 }
let str = 'banana';
const sumByChar = str.split('').reduce((acc, char) => ({
//use split to convert string to array of characters

...acc,
//using the spread operator on the accumulator will
give us access to all the properties in the object
[char]: (acc[char] || 0) + 1,
// creating the element as a key - initializing to 1
if it does not exist, incrementing by 1 if it does
}), {});
//initial value is an empty object
console.log(sumByChar) // { b: 1, a: 3, n: 2 }
let str = ''for(let char of str){
str = char + str
//starts as empty string and accumulates one by one
//'' = h + ''
//h = e + h
//eh = l + eh
//leh = l + leh
//lleh = o + lleh
//olleh
}
console.log('hello') // prints olleh
let reversed = (str) => str.split('').reduce((acc,char) => char + acc)
//accumulator starts empty and adds on one by one. if string, use .split('') to convert to array.
//'' = h + ''
//h = e + h
//eh = l + eh
//leh = l + leh
//lleh = o + lleh
//olleh
console.log(reversed('hello')) // prints olleh
let flattenArray = (arr) => {
return arr.reduce((total, curr) => {
return total.concat(Array.isArray(curr) ? flattenArray(curr) : curr);

//if the value is an array, the recursively call reduce until next nested array
//if the value is not an array, then just concatenate the value to the flattened array.

//total [] curr 2
//total [ 2 ] curr 1
//total [ 2, 1 ] curr [ 3, 10, [ 12 ] ]
//total [] curr 3
//total [ 3 ] curr 10
//total [ 3, 10 ] curr [ 12 ]
//total [] curr 12

//returns [ 2, 1, 3, 10, 12 ]
}, []);
//initial value is an empty array
}console.log(flattenArray([2, 1, [3, 10, [12]]]))
// returns [2, 1, 3, 10, 12]

--

--

Get smarter at building your thing. Follow to join The Startup’s +8 million monthly readers & +768K followers.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store