Inventory Update

題目:
  Inventory是庫存、存貨清單、財產目錄或詳細目錄的意思,而這題就是要我們用程式模擬進出貨的統計,重複的貨物需要統計數量,新的貨物必須加入現有貨物清單中

function updateInventory(arr1, arr2) {
    // All inventory must be accounted for or you're fired!
    var invListObj = {};
    arr1.forEach(function(item)
                 {
                     invListObj[item[1]] = item[0];
                 });
    arr2.forEach(function(emt)
                 {
                     if(invListObj.hasOwnProperty(emt[1]))
                        invListObj[emt[1]] += emt[0];
                     else
                        invListObj[emt[1]] = emt[0];
                  });
    arr1 = [];
    var key  = Object.keys(invListObj).sort();
    for(var i=0;i < key.length;i++)
    {
        arr1.push([invListObj[key[i]], key[i]]);
    }
    return arr1;
}

// 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(curInv, newInv);

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"]].

Solution:

  這題我的作法是先建立一個空的Object,然後將arr1中的現有貨物用Object member名稱紀錄貨物名稱,值為member所對應的值,用key value的方式對應,然後用forEach訪問新的arr2的每個元素,再依據Object property 來查找是否具有此項貨物,有則更新數量,沒有則新增property及對應的值(貨物數量),最後再用Object.keys(ObjectName).sort()來取得所也Object屬性並排序(題目要求依照貨物的名稱的Alphabet順序排列),然後依序push(放)進arr1(現有貨物array清單)中



**P.S. / Reference:  Global Array Object

results matching ""

    No results matching ""