Reduce may be one of the trickier Array methods to wrap your head around, luckily though it is not that difficult to understand. The Reduce method gives you the ability to complete restructure array data into any format you need. Another note to remember is that reduce does not mutate the original array.
const data = [1,2,3,4,5]; const sum = data.reduce((accumulator, curr, index, initialArr) => { return accumulator + curr; }, 0) console.log(sum) // sum : 15
Console:
To use reduce, first we call reduce on the original array. We pass a callback function to reduce accepts 4 optional arguments, and an initial value to be passed to the first callback call.
accumulator - Value returned from the previous callback item - The current item in the array as we loop through index - The current index in the array as we loop through initialArr - The initial array that reduce was called on
So as we loop through the array, the callback gets called on each array item. Whatever gets returned from the callback function is then passed back into the callback on the next call.
const data = [1, 2, 3, 4, 5]; const convertToObject = data.reduce((acc, curr) => { return {...acc, ...{[curr]: curr}} }, {}) console.log(convertToObject) // convertToObject : {1:1, 2:2, 3:3, 4:4, 5:5}
Console:
const data = [1, 2, 3, 4, 5]; const convertToArrayOfObjects = data.reduce((acc, curr) => { return [...acc, {key: curr}] }, []) console.log(convertToArrayOfObjects) // convertToArrayOfObjects :[ {key:1}, {key:2}, {key:3}, {key:4}, {key:5}]
Console:
const data = ['Hello', 'world', 'i', 'hope','you', 'are', 'ok']; const convertToString = data.reduce((acc, curr) => { return acc + ' ' + curr; }, '') console.log(convertToString) // convertToString: 'Hello world i hope you are ok'
Console:
const data = [1, 2, 3, 4, 5]; const convertToMap= data.reduce((acc, curr) => { return acc.set(curr, curr); }, new Map()) console.log(convertToMap.get(1)) // 1
Console:
Reduce is a powerful tool and is very easy to use, it just requires a callback function and an understanding of how you want to reshape your data. Now get out there and start reducing!