I have an array of hashes...
array = [
{
'keyword' => 'A',
'total_value' => 50
},
{
'keyword' => 'B',
'total_value' => 25
},
{
'keyword' => 'C',
'total_value' => 40
},
{
'keyword' => 'A',
'total_value' => 10
},
{
'keyword' => 'C',
'total_value' => 15
}]
I need to consolidate the hashes with an identical keyword
value. By consolidate, I mean combine total_values
. For example, after consolidation of the above array, there should only be one hash with 'keyword' => 'A'
with a 'total_value => 60
Output:
Here is how it can be done:
A simple method is doing this as you add items to a collection. Start to add an item, check if keyword is there. if (a) it's there, then just add new item's total_value to its. else (b) add new item to the collection.