js reduce method

js reduce method

The reduce method is used to reduce an array to a single value.

In reduce, the first argument is an accumulator value representing the value the array will be reduced to. reduce can also receive an initial value for the accumulated value

to sum

const arr = [5, 7, 4, 2]
const sum = arr.reduce((a, b) => {
    
    
    a += b
    return a
}, 0);
console.log(sum);

initial letter of each word

const words = ["Beach", "Random", "Angle", "Clever", "None"];
const alph = words.reduce((a, x) => {
    
    
    a[x[0]] = x;
    return a
}, {
    
    })
console.log(alph);

Guess you like

Origin blog.csdn.net/m0_48546501/article/details/130387908