1var objs = [
2 {name: "Peter", age: 35},
3 {name: "John", age: 27},
4 {name: "Jake", age: 28}
5];
6
7objs.reduce(function(accumulator, currentValue) {
8 return accumulator + currentValue.age;
9}, 0); // 35 + 27 + 28 = 90
1const posts = [
2 {id: 1, category: "frontend", title: "All About That Sass"},
3 {id: 2, category: "backend", title: "Beam me up, Scotty: Apache Beam tips"},
4 {id: 3, category: "frontend", title: "Sanitizing HTML: Going antibactirial on XSS attacks"}
5];
6
7const categoryPosts = posts.reduce((acc, post) => {
8 let {id, category} = post;
9 return {...acc, [category]: [...(acc[category] || []), id]};
10}, {});
11
1var arr = [{x:1},{x:2},{x:4}];
2
3arr.reduce(function (a, b) {
4 return {x: a.x + b.x}; // returns object with property x
5})
6
7// ES6
8arr.reduce((a, b) => ({x: a.x + b.x}));
9
10// -> {x: 7}
1arr.reduce(callback( accumulator, currentValue[, index[, array]] )[, initialValue])
2