Here's a thought I have:
If we have an array of objects like this:
[
{
"name": "Kirk",
"count": 1
},
{
"name": "Spock",
"count": 1
},
{
"name": "Kirk",
"count": 1
}
]
I would like to achieve this result:
[
{
"name": "Kirk",
"count": 2
},
{
"name": "Spock",
"count": 1
}
]
I am interested in finding an algorithm that could potentially leverage higher order functions for this task. While using loops is possible, my goal is to explore more elegant solutions with higher order functions. Any guidance on the specific methods or techniques I should consider for this problem would be greatly appreciated. My preference is for a solution that is as concise and expressive as possible (avoiding complex combinations of maps and filters).
This is my current approach, but I believe there may be room for improvement:
function mergeDuplicates(input) {
var output = [];
var existingItem = null;
input.forEach(function (inputItem) {
existingItem = _.find(output, function (outputItem) {
return inputItem.name === outputItem.name;
});
existingItem ? existingItem.count += 1 : output.push({
name: inputItem.name,
count: 1
});
existingItem = null;
});
return output;
}
Just to clarify line #10: if the original array has no 'count' property or it is initially set to 1, I default it to 1.