reduce javascript sum code example

Example 1: javascript reduce sum

arrSum = function(arr){  return arr.reduce(function(a,b){    return a + b  }, 0);}

Example 2: javascript reduce sum

let nums = [1, 2, 3];

nums.reduce((curr, next) => curr + next);

Example 3: reduce array to object javascript

const posts = [
    {id: 1, category: "frontend", title: "All About That Sass"},
    {id: 2, category: "backend", title: "Beam me up, Scotty: Apache Beam tips"},
    {id: 3, category: "frontend", title: "Sanitizing HTML: Going antibactirial on XSS attacks"}
];

const categoryPosts = posts.reduce((acc, post) => {
    let {id, category} = post;
    return {...acc, [category]: [...(acc[category] || []), id]};
}, {});

Example 4: .reduce mdn

arr.reduce(callback( accumulator, currentValue[, index[, array]] )[, initialValue])

Example 5: reduce javascript

//note idx and sourceArray are optional
const sum = array.reduce((accumulator, element[, idx[, sourceArray]]) => {
	//arbitrary example of why idx might be needed
	return accumulator + idx * 2 + element 
}, 0);