題目:數組
依照一個存着新進貨物的二維數組,更新存着現有庫存(在 arr1
中)的二維數組. 若是貨物已存在則更新數量 . 若是沒有對應貨物則把其加入到數組中,更新最新的數量. 返回當前的庫存數組,且按貨物名稱的字母順序排列.spa
當你遇到困難的時候,記得查看錯誤提示、閱讀文檔、搜索、提問。code
這是一些對你有幫助的資源:對象
1 function updateInventory(arr1, arr2) { 2 // All inventory must be accounted for or you're fired! 3 4 5 var arr = []; // 用於存放當前貨物名稱的數組 6 var obj = {}; // 用於存放當前貨物名稱和數組下標的對象 7 var arr1Len = arr1.length - 1; 8 9 // 遍歷當前貨物的名稱,下標和名稱 10 for (var i = 0; i < arr1.length; i++) { 11 arr.push(arr1[i][1]); 12 obj[arr1[i][1]] = i; 13 } 14 15 // 更新當前數組 16 for (var j = 0; j < arr2.length; j++) { 17 // 若是新進貨物已存在,更新數量(加法) 18 if (arr.indexOf(arr2[j][1]) !== -1) { 19 var arr1Index = obj[arr2[j][1]]; 20 arr1[arr1Index][0] += arr2[j][0]; 21 } 22 // 若是新進貨物不存在,加入到當前貨物數組 23 else { 24 arr1.push(arr2[j]); 25 // 更新arr、obj 26 arr.push(arr2[j][1]); 27 arr1Len += 1; 28 obj[arr2[j][1]] = arr1Len; 29 } 30 } 31 32 //排序 33 arr.sort(); 34 var result = []; 35 for (var z = 0; z < arr.length; z++) { 36 result.push(arr1[obj[arr[z]]]); 37 } 38 return result; 39 40 } 41 42 // Example inventory lists 43 // arr1 44 var curInv = [ 45 [21, "Bowling Ball"], 46 [2, "Dirty Sock"], 47 [1, "Hair Pin"], 48 [5, "Microphone"] 49 ]; 50 //arr2 51 var newInv = [ 52 [2, "Hair Pin"], 53 [3, "Half-Eaten Apple"], 54 [67, "Bowling Ball"], 55 [7, "Toothpaste"] 56 ]; 57 58 updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]);
updateInventory()
應該返回一個數組.
updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]).length
應該返回一個長度爲6的數組.
updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])
應該返回
[[88, "Bowling Ball"], [2, "Dirty Sock"], [3, "Hair Pin"], [3, "Half-Eaten Apple"], [5, "Microphone"], [7, "Toothpaste"]]
.
updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [])
應該返回
[[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]]
.
updateInventory([], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]])
應該返回
[[67, "Bowling Ball"], [2, "Hair Pin"], [3, "Half-Eaten Apple"], [7, "Toothpaste"]]
.
updateInventory([[0, "Bowling Ball"], [0, "Dirty Sock"], [0, "Hair Pin"], [0, "Microphone"]], [[1, "Hair Pin"], [1, "Half-Eaten Apple"], [1, "Bowling Ball"], [1, "Toothpaste"]])
應該返回
[[1, "Bowling Ball"], [0, "Dirty Sock"], [1, "Hair Pin"], [1, "Half-Eaten Apple"], [0, "Microphone"], [1, "Toothpaste"]]
.