Created
January 22, 2019 10:11
-
-
Save erkanzileli/6ad701edd8c79efce7ac496adec62374 to your computer and use it in GitHub Desktop.
Merge objects of the same key name in arrays
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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