javascript - Inventory update challenge -


i'm trying solve algorithm challenge.

here prompt:

compare , update inventory stored in 2d array against second 2d array of fresh delivery. update current existing inventory item quantities (in arr1). if item cannot found, add new item , quantity inventory array. returned inventory array should in alphabetical order item.

here code:

function updateinventory(arr1, arr2) {     // inventory must accounted or you're fired!    var mymap = new map();    (var = 0; < arr1.length; i++){     mymap.set(arr1[i][1], arr1[i][0]);   }    (i = 0; < arr2.length; i++){     if (!mymap.has(arr2[1])){       mymap.set(arr2[i][1], 0);     }     mymap.set(arr2[i][1], mymap.get(arr2[i][1]) + arr2[i][0]);       }    var arr3 = [];    // sorting   mymap.foreach(function(value, key){     var = 0;      while (i < arr3.length && key > arr3[i][1])       i++;      arr3.splice(i, 0, [value, key]);   });    return arr3;  }  // 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); 

https://jsfiddle.net/5fvgdl84/

here should happen:

updateinventory([[21, "bowling ball"], [2, "dirty sock"], [1, "hair pin"], [5, "microphone"]], [[2, "hair pin"], [3, "half-eaten apple"], [67, "bowling ball"], [7, "toothpaste"]])

should return

[[88, "bowling ball"], [2, "dirty sock"], [3, "hair pin"], [3, "half-eaten apple"], [5, "microphone"], [7, "toothpaste"]].

edit: think i've got solution. however, there seems bug in code can't seem find. need specifically.

you can use map if want, did similar creating object 'current' array maintain reference, makes things lot easier since function apparently can't return new object replace 'current' with.

// example inventory lists var current = [     [21, "bowling ball"],     [2, "dirty sock"],     [1, "hair pin"],     [5, "microphone"] ];  var updated = [     [2, "hair pin"],     [3, "half-eaten apple"],     [67, "bowling ball"],     [7, "toothpaste"] ];  function toobj(arr){   var obj = {};   arr.foreach((item) => {     obj[item[1]] = item[0];   });   return obj; }  function updateinventory(current, updated){   var inventory = toobj(current);   updated.foreach((item) => {     inventory[item[1]] = item[0];   });    current.length = 0;    object.keys(inventory).foreach((key) => {     var count = inventory[key];     current.push([count, key]);   }); }  updateinventory(current, updated); console.log(current); 

that creates correct replacement of current inventory.

https://jsfiddle.net/t6x5eag4/


Comments