Skip to content

Instantly share code, notes, and snippets.

@erkanzileli
Created January 22, 2019 10:11
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 erkanzileli/6ad701edd8c79efce7ac496adec62374 to your computer and use it in GitHub Desktop.
Save erkanzileli/6ad701edd8c79efce7ac496adec62374 to your computer and use it in GitHub Desktop.
Merge objects of the same key name in arrays
var customMergeObjectsWithSameKeys = function (arr, key, mergeFunction) {
var _arr = []
arr.forEach(item => {
var index = _arr.findIndex(_item => _item[key] === item[key])
if (index === -1) {
_arr.push(item)
} else {
_arr[index] = mergeFunction(_arr[index], item)
}
})
return _arr
}
// Example
customMergeObjectsWithSameKeys(data, 'date', (item, _item) => ({
...item,
cost: Number(item.cost) + Number(_item.cost),
duration: Number(item.duration) + Number(_item.duration)
}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment