Reduce

Reduce

Array.reduce() will iterate through each value from the array and return a single value, single array or single object.

Reduce to 1 single value

Return the total values of the array.

const numbers = [1, -1, 2, 5];

// Normal sum using loop.
let sum = 0;
for(let n of numbers) {
    sum +=n;
}
console.log({sum});

// https://www.youtube.com/watch?v=g1C40tDP0Bk
// Sum using reduce(): Reduce to 1 single value
//  Reduce takes 2 arguements: callback function and initial accumulator value = 0.
//      accumulator(previous return value) = sum, currentValue = each value in numbers[].
//  If initial accumulator is not provided, then it will use the 1st value in numbers[] as the initial accumulator.
//  For my case, I initialize to 0.
const sum2 = numbers.reduce( (accumulator, currentValue) => {
                                    return accumulator + currentValue;
                                }, 0);
console.log({sum2}); // 7

Reduce to an array with different size

Return an array where each value is greater than 10.

const collection = [3, 5, 11, 23, 1];

// filter all the elements bigger than 10 to a new array
const biggerThan10 = collection.reduce(function (filteredArr, collectionValue) {
    if (collectionValue > 10) {
        filteredArr.push(collectionValue);
    }
    return filteredArr; // Must return accumulator.
}, []);

console.log({biggerThan10}); // [ 11, 23 ]

Convert array values to an object keys

const arrayList = [3, 5, 11, 23, 1];
const arrayObject = collection.reduce(function (accumulator, currentValue) {
                                            accumulator[currentValue] = currentValue
                                            return accumulator; // Must return accumulator.
                                        }, {}); // Initialize accumulator as an object.

console.log({ arrayObject });
/*
// Output
{
    "1": 1,
    "3": 3,
    "5": 5,
    "11": 11,
    "23": 23
}
*/