I have an array of arrays i.e:
const arrayDaddy = [[x, 1], [x, 1], [y, 2], [y, 2], [y, 2], [z, 3]]
my end goal is to take the above arrayDaddy
and mutate it by adding the number in arrayDaddy[i][1]
if the two items have the same value arrayDaddy[i][0]
. Additionally, I want to throw out nested arrays with repeated arrayDaddy[i][0]
values after they have been added. The desired result of this process on arrayDaddy
would be as follows:
arrayDaddy = [[x, 2], [y, 6], [z, 3]]
I am wondering if there is a way to use Array.prototype.reduce();
to achieve this. If not, what is a simple way to achieve this goal?
NOTE: not sure if this is important, but all items with the same value in index 0 will share an index 1 value. for example consider [z, 3]. any addition [z, ] items will also have a 3 in index 1.
I did try reduce();
but did not have success. my code looked something like this:
const arrayDaddy = [[x, 1], [x, 1], [y, 2], [y, 2], [y, 2], [z, 3]] ;
arrayDaddy.reduce((arr1, arr2) => {
if(arr1[0] === arr2[0]){
arr1[1] += arr2[1]
// do something here to delete arr2... but I can't use delete on a local variable?
} else {
//do nothing, continue to the next arr in arrayDaddy
}
});
I also considered map, but want to avoid creating a new array. I want to mutate the arrayDaddy