【FCC】Inventory Update
題目:
依照一個(gè)存著新進(jìn)貨物的二維數(shù)組,更新存著現(xiàn)有庫(kù)存(在 arr1 中)的二維數(shù)組. 如果貨物已存在則更新數(shù)量 . 如果沒有對(duì)應(yīng)貨物則把其加入到數(shù)組中,更新最新的數(shù)量. 返回當(dāng)前的庫(kù)存數(shù)組,且按貨物名稱的字母順序排列.
示例:
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 應(yīng)該返回一個(gè)長(zhǎng)度為6的數(shù)組.
updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]) 應(yīng)該返回 [[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"]], []) 應(yīng)該返回 [[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]].
updateInventory([], [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]]) 應(yīng)該返回 [[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"]]) 應(yīng)該返回 [[1, "Bowling Ball"], [0, "Dirty Sock"], [1, "Hair Pin"], [1, "Half-Eaten Apple"], [0, "Microphone"], [1, "Toothpaste"]].
分析思路:
遍歷進(jìn)貨數(shù)組,取每一個(gè)元素,然后遍歷庫(kù)存數(shù)組,若進(jìn)貨的名稱已存在,直接修改數(shù)目,若進(jìn)貨的名稱不存在,這 push 到庫(kù)存中;
從測(cè)試用例中可知:最終的庫(kù)存列表需要根據(jù)名稱進(jìn)行排序,從字符的低到高進(jìn)行排序;
代碼:
<script type="text/javascript">
function updateInventory(arr1, arr2) {
// All inventory must be accounted for or you're fired!
for (var i = 0; i < arr2.length; i++) {
for (var j = 0; j < arr1.length; j++) {
if (arr1[j][1] === arr2[i][1]) {
arr1[j][0] += arr2[i][0];
break;
}
}
if (j == arr1.length) {
arr1.push(arr2[i]);
}
}
return arr1.sort(function(a, b) {
return a[1].charCodeAt(0) - b[1].charCodeAt(0);
});
}
</script>
總結(jié)
以上是生活随笔為你收集整理的【FCC】Inventory Update的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【FCC】Exact Change 收银
- 下一篇: 【FCC】No repeats plea