Reduce functions

PHOTO EMBED

Wed May 29 2024 01:09:41 GMT+0000 (Coordinated Universal Time)

Saved by @RahmanM

// first parameter is the Accumulator and 2nd is the current value
let result = [1, 2, 3, 4].reduce(function (a, b) {
    //console.log(a, b)
    return a + b;
});

result

// get total of the all items
let products = [
    { name: "Cucumber", type: "vegetable", price: 45.0 },
    { name: "Banana", type: "fruit", price: 20.0 },
    { name: "Carrot", type: "vegetable", price: 20.0 },
    { name: "Apple", type: "fruit", price: 75.0 }
];


let total = products.reduce((total, product) => {
    return total + product.price
}, 0)

total

// create a dictionary of the products by name

let lookup = products.reduce((dictionary, product) => {
    dictionary[product.name] = product; // fixed the syntax error
    return dictionary;
}, {});

console.log(lookup["Banana"].type) // lookup["Banana"].price


let people = [
    { name: "Jane", age: 34 },
    { name: "Mark", age: 20 },
    { name: "Abby", age: 20 },  
]


// group by age

let groupedByAge = people.reduce((dictionary, person) => {
    dictionary[person.age] = dictionary[person.age] || []; // fixed the syntax error
    dictionary[person.age].push(person);
    return dictionary;
}, {});


groupedByAge


// Extra parameters

let test = [1, 2, 3, 4].reduce(function (accumulator, item, index, array) {
    console.log(index)
    console.log(array)
    return accumulator + item;
}, 0);
content_copyCOPY