I am trying to do this challenge in FCC, inventory update.
Only problem I am facing is that, when I want to push the new element from the new array to the old array, it is giving me timeout. Adding the numbers if the element matches works fine though.
Here is what I have done so far.
//sorting the 2D array
function sortingArray(a,b){
if (a[1] === b[1]) {
return 0;
}
else {
return (a[1] < b[1]) ? -1 : 1;
}
}
function updateInventory(arr1, arr2) {
if (arr1.length === 0) {
return arr2.sort(sortingArray)
}
if (arr2.length === 0) {
return arr1.sort(sortingArray)
}
for (let i = 0; i < arr2.length; i++) {
for (let j = 0; j < arr1.length; j++) {
if (arr2[i][1] === arr1[j][1]) {
arr1[j][0] = arr1[j][0] + arr2[i][0] //adding the numbers if it matches
}
if(arr2[i][1] != arr1[j][1]){
arr1.push(arr2[i]) //pushing the unique element
}
}
}
console.log(arr1)
return arr1.sort(sortingArray);
}
// 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);