Skip to content

Instantly share code, notes, and snippets.

@92hackers
Last active August 22, 2017 09:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 92hackers/a45cfaba1f58853a584f60ce0dfc06ae to your computer and use it in GitHub Desktop.
Save 92hackers/a45cfaba1f58853a584f60ce0dfc06ae to your computer and use it in GitHub Desktop.
Javascript reduce function and dynamic keys in es6 format

Objects can be created with computed keys, so es6.ruanyifeng.com is not enough.

const obj = {
  [variable]: value,
}

Reduce, the simplest way to accummulate datas. reduce set first item as initial value default.

const total = ['age', 'name', 'favourite'].map(key => dataLists.reduce((sum, data) => ({
  [key]: +sum[key] + parseFloat(data[key])
})))

from code above, if you want to convert a string to number, just place an + plus operator before the string

Above code can be refactored, expense too much

const keys = ['age', 'name', 'favourite']
dataList.reduce((sum, data) => {
  return keys.reduce((count, key) => {
    count[key] = +sum[key] + parseFloat(data[key])
    return count
  }, {})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment