Skip to content

Instantly share code, notes, and snippets.

@masatomix
Last active March 19, 2020 01:05
Show Gist options
  • Save masatomix/b8b2a388f10f5862ace9bd72fff234e9 to your computer and use it in GitHub Desktop.
Save masatomix/b8b2a388f10f5862ace9bd72fff234e9 to your computer and use it in GitHub Desktop.
Reduceのサンプル. 収集するaccumulatorと初期値を設定するのが重要
const array1 = [1, 2, 3, 4,5];
const reducer = (accumulator, currentValue,index) => {
console.log(`---`)
console.log(`Index: ${index}`)
console.log(`A: ${accumulator}`)
console.log(`C: ${currentValue}`)
return {value: accumulator.value + currentValue}
return accumulator+currentValue
}
// 1 + 2 + 3 + 4
console.log(JSON.stringify(array1.reduce(reducer,{value:0})));
// expected output: 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment