Created
October 17, 2019 17:05
-
-
Save tianmingzuo/f3be5dfebd19eadf29898af5ffaf18bf to your computer and use it in GitHub Desktop.
Inventory Update: 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function updateInventory(arr1, arr2) { | |
| let updatedArr = []; | |
| if(arr1 === []){ | |
| updatedArr = arr2; | |
| }else if(arr2 === []) { | |
| updatedArr = arr1; | |
| }else{ | |
| let newItemArr = []; | |
| for(let i=0; i<arr2.length; i++){ | |
| let flag = false; | |
| for(let j=0; j<arr1.length; j++){ | |
| if(arr2[i][1] === arr1[j][1]){ | |
| flag = true; | |
| arr1[j][0] += arr2[i][0]; | |
| } | |
| } | |
| if(!flag){ | |
| newItemArr.push(arr2[i]); | |
| } | |
| } | |
| updatedArr = arr1.concat(newItemArr) | |
| } | |
| for(let i=0; i<updatedArr.length; i++){ | |
| updatedArr[i].reverse(); //prepare for sorting alphabetical order | |
| } | |
| updatedArr.sort(); //sort according to alphabetical order by item. | |
| for(let i=0; i<updatedArr.length; i++){ | |
| updatedArr[i].reverse(); //reverse back to original format after sorting | |
| } | |
| return updatedArr; | |
| } | |
| // 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([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], []) should return [[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]]. | |
| Passed | |
| updateInventory([], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]) should return [[67, "Bowling Ball"], [2, "Hair Pin"], [3, "Half-Eaten Apple"], [7, "Toothpaste"]]. | |
| Passed | |
| updateInventory([[0, "Bowling Ball"], [0, "Dirty Sock"], [0, "Hair Pin"], [0, "Microphone"]], [[1, "Hair Pin"], [1, "Half-Eaten Apple"], [1, "Bowling Ball"], [1, "Toothpaste"]]) should return [[1, "Bowling Ball"], [0, "Dirty Sock"], [1, "Hair Pin"], [1, "Half-Eaten Apple"], [0, "Microphone"], [1, "Toothpaste"]]. | |
| */ | |
| updateInventory(curInv, newInv); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment