Dear Sir or Madame,
I had a different solution to the problem which I think might interest you.
Generally I try to solve every looping with the array functions .filter(), .map() and .reduce(). I am from Hungary so at some point I might made some mistakes in the explanation, feel free to correct it if you found my solution worth to post it as a sample solution.
Yours faithfully
Nándor MIHÁLY
Solution
function updateInventory(arr1, arr2) {
// first of all map through the curInv array to either preserve or update the count of its elements
let arr = arr1.map(currInvElement => {
return !arr2.some(element => element[1] === currInvElement[1]) // if there is no element in the newInv array, that matches the curInv array's element
? currInvElement // then preserve the element as it is
: [
currInvElement[0] + arr2.filter(newInvElement => currInvElement[1] == newInvElement[1])[0][0], //otherwise find the matching elements in both arrays and sum their count as the 0th element of the array
currInvElement[1] // and take the name of the element as the 1st element of the returned array
]
})
// now let's add the items which are only in the newInv array
arr = arr.concat(arr2
.filter(elem => !arr.some(el => el[1] == elem[1])))
.sort((a, b) => { //then sort them alphabetically
return a[1] === b[1]
? 0
: a[1] < b[1]
? -1
: 1 });
console.log(arr); // check your result
return arr;
}
// Example inventory lists
var curInv = [
[21, "Bowling Ball"],
[2, "Dirty Sock"],
[1, "Hair Pin"],
[5, "Microphone"]
];
var newInv = [
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[67, "Bowling Ball"],
[7, "Toothpaste"]
];
updateInventory(curInv, newInv);