Skip to content

Instantly share code, notes, and snippets.

@rfprod
Last active April 22, 2017 15:52
Show Gist options
  • Save rfprod/025109541a9bde80636a to your computer and use it in GitHub Desktop.
Save rfprod/025109541a9bde80636a to your computer and use it in GitHub Desktop.
Inventory Update
function inventory(arr1, arr2) {
var addItems = [];
var existingItems = [];
var i,j;
// update existing items and detect existing items
for (i=0;i<arr1.length;i++){
for (j=0;j<arr2.length;j++){
if (arr1[i][1] == arr2[j][1]){
arr1[i][0] = arr1[i][0] + arr2[j][0];
existingItems.push(arr2[j][1]);
}
}
}
// detect new items to be added to inventory
for (j=0;j<arr2.length;j++){
if (existingItems.indexOf(arr2[j][1]) == -1){addItems.push(arr2[j]);}
}
// push new items to inventory
for (j=0;j<addItems.length;j++){arr1.push(addItems[j]);}
// sort final arr1
arr1.sort(function(a,b){
if(a[1] < b[1]) return -1;
if(a[1] > b[1]) return 1;
return 0;
});
return arr1;
//return addItems;
//return arr1InsertIndex;
//return JSON.stringify(addItems);
}
//inventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]);
//inventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"], [6, "Zoom"]]);
inventory([], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]);

Inventory Update

Function compares and updates inventory stored in a 2d array against a second 2d array of a fresh delivery. It updates current inventory item quantity, and if an item cannot be found, adds the new item and quantity into the inventory array in alphabetical order.

A script by V.

License.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment