Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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) {
// All inventory must be accounted for or you're fired!
//check the items in arr2 against those in arr1
//if the item is found update the value and set found to true.
//if the item is not found add it to arr1
for(var i = 0; i < arr2.length; i++){ //loop over array 2
var found = false;
for(var j = 0; j<arr1.length; j++){ //loop over array 1
if(arr2[i][1] === arr1[j][1]){
arr1[j][0] = arr1[j][0] + arr2[i][0];
found = true;
}
}
if(!found){
arr1.push(arr2[i]);
}
}
//now sort the array by the second column of the multidimensional array.
return arr1.sort(function(a, b){
if (a[1] < b[1]) {
return -1;
}
if (a[1] > b[1]) {
return 1;
}
// names must be equal
return 0;
});
}
// 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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.