arr.reduce(callback[, initialValue])
callback : 배열의 각 요소에 대해 실행할 함수이며 4가지 인수를 받는다
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
return accumulator + currentValue;
});
const result = [0,1,2,3].reduce((acc, curr) => {return cur + acc},0)
const result = [0,1,2,3].reduce((acc,curr) => acc + curr,0)
const result = [{x:1},{x:2},{x:3}].reduce(function (acc,curr) {
return acc + curr.x
},initialValue)
console.log(result) // 6
const result = [[0, 1], [2, 3], [4, 5]].reduce(function (acc, curr) {
return acc.concat(curr)
},[])
const result = [[0, 1], [2, 3], [4, 5]].reduce(
(acc, curr) => acc.concat(curr), []
)
const name = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
const countedNames = names.reduce((allNames, curr) => {
if(name in allNames) {
allNames[name] ++;
}else{
allNames[name] = 1;
}
return allNames;
},{})
const people = [
{ name: 'Alice', age: 21 },
{ name: 'Max', age: 20 },
{ name: 'Jane', age: 20 }
];
function groupBy(objectArray, property) {
return objectArray.reduce(function (acc, obj) {
const key = obj[property];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj);
return acc;
}, {});
}
const groupedPeople = groupBy(people, 'age');
// Building-blocks to use for composition
const double = x => x + x;
const triple = x => 3 * x;
const quadruple = x => 4 * x;
// Function composition enabling pipe functionality
const pipe = (...functions) => input => functions.reduce(
(acc, fn) => fn(acc),
input
);
// Composed functions for multiplication of specific values
const multiply6 = pipe(double, triple);
const multiply9 = pipe(triple, triple);
const multiply16 = pipe(quadruple, quadruple);
const multiply24 = pipe(double, triple, quadruple);
// Usage
multiply6(6); // 36
multiply9(9); // 81
multiply16(16); // 256
multiply24(10); // 240