I have a 2D array:
var arr1 = [["Egypt","Grid",50],["Egypt","Grid",10],["Nigeria","Grid",20],["Ghana","Grid",60],["Egypt","Grid",30]]
I want to check the first element of each array, e.g. Egypt, Nigeria and Ghana to see if they are duplicates. But I only want it to check against the next element not against all elements in the array. If one or more elements are duplicated next to each other, I want to return one array summing the elements at position 2 (50,10,20,60,30)
This should result in :
var arr2 = [["Egypt","Grid",60],["Nigeria","Grid",20],["Ghana","Grid",60]],["Egypt","Grid",30]]
Note how even though there are 3 arrays with "Egypt", it only combines where they are next to each other.
I have tried both map and for loop but don't have anything that is close to working. This is what I've started with:
arr1.map(function (unit, index, array) {
var length = array.length
if (index < length - 2) {
var next = array[index + 1][0]
if (unit[0] === next) {
}
}
})
This works to check if elements are duplicates. I think I need to next put the duplicates into a separate array which I can then reduce but am not sure how to do that. Any help in pointing me in the right direction would be great. Thanks!