依照一個(gè)存著新進(jìn)貨物的二維數(shù)組二拐,更新存著現(xiàn)有庫存(在 arr1 中)的二維數(shù)組. 如果貨物已存在則更新數(shù)量 . 如果沒有對應(yīng)貨物則把其加入到數(shù)組中舀寓,更新最新的數(shù)量. 返回當(dāng)前的庫存數(shù)組,且按貨物名稱的字母順序排列.
function updateInventory(curInv, newInv) {
// 請保證你的代碼考慮到所有情況
curInv.forEach(function(elementC,indexC){
newInv.forEach(function(elementN,indexN){
if(elementN[1]===elementC[1]){
elementC[0] += elementN[0];
newInv.splice(indexN,1);
}
});
});
//連接兩個(gè)數(shù)組
curInv = curInv.concat(newInv);
function letterSort(arr){
arr.forEach(function(e,i){
arr[i].unshift(arr[i][1]);
arr[i].pop();
});
arr.sort();
arr.forEach(function(e,i){
arr[i].unshift(arr[i][1]);
arr[i].pop();
});
return arr;
}
return letterSort(curInv);
}
// 倉庫庫存示例
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);