(please suggest improvements).
Challenge: Compare and update the inventory stored in a 2D array against a second 2D array of a fresh delivery. Update the current existing inventory item quantities (in arr1
). If an item cannot be found, add the new item and quantity into the inventory array. The returned inventory array should be in alphabetical order by item.
function updateInventory(arr1, arr2) {
//Nested Function to check if new item is present in current inventory if yes then update current inventory. else return True.
function itemCheck(a, b){
let result = true;
for (let j = 0; j < b.length; j++){
if (b[j].includes(a[1])){
b[j][0] += a[0];
result = false;
}
}
return result;
}
// Compare function to arrange alphabetically.
function compareFunction (a, b){
return a[1] === b[1] ? 0: a[1] < b[1] ? -1: 1;
}
//Update current inventory
for (let i = 0; i < arr2.length; i++){
if (itemCheck(arr2[i], arr1)){
arr1.push(arr2[i]);
}
}
//Alphabetical order.
arr1.sort(compareFunction);
return arr1;
}
// 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);