LoginSignup
0

More than 5 years have passed since last update.

JavaScript Functional Programming memo

Last updated at Posted at 2019-02-16

JavaScript Functional Programming memo

map

const numbers = [1,2,3,4,5,6]

numbers.map(function(n) {return n*n;})
> [ 1, 4, 9, 16, 25, 36 ]

numbers.map((n) => { return n*n; })
> [ 1, 4, 9, 16, 25, 36 ]

numbers.map(n => n*n)
> [ 1, 4, 9, 16, 25, 36 ]

filter

const numbers = [1,2,3,4,5,6]

numbers.filter((n) => { return n<5; })
> [ 1, 2, 3, 4 ]

numbers.filter(n => n<5)
> [ 1, 2, 3, 4 ]

reduce

const numbers = [1,2,3,4,5,6]

// reduce's callback function's returned value is automatically assigned to the accumulator.
numbers.reduce((acc, n) => acc * n, 1)
> 720

numbers.reduce((acc, n) => acc + n, '')
> '123456'

// acc is automatically assigned, so the following version is verbose.
// keep this verbose-version just for reminding myself.
// useless version
numbers.reduce((acc, n) => {acc[n]=n*n; return acc;}, {})
> { '1': 1, '2': 4, '3': 9, '4': 16, '5': 25, '6': 36 }

// compact version
numbers.reduce((acc, n) => ({...acc, [n]:n*n }), {})
> { '1': 1, '2': 4, '3': 9, '4': 16, '5': 25, '6': 36 }

// compact version
numbers.reduce((acc, n) => [...acc, n*n], [])
> [ 1, 4, 9, 16, 25, 36 ]

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0