Antonio Ortiz Antonio Ortiz - 7 months ago 20
Javascript Question

How do I compare and update this array based on another array in JavaScript?

I am working on this challenge—Inventory update, on Free CodeCamp.com
The challenge states:


Compare and update the inventory stored in a 2D array against a second
2D array of a fresh delivery. Update the current existing inventory
item quantities (in arr1). If an item cannot be found, add the new
item and quantity into the inventory array. The returned inventory
array should be in alphabetical order by item.


function updateInventory(arr1, arr2) {
for (var x = 0; x < arr1.length; x++) {

for (var y = 0; y < arr2.length; y++) {

if (arr1[x][1] === arr2[y][1]) {
arr1[x][0] = arr2[y][0] + arr1[x][0];
}
}
}

for(var j = 0; j < arr2.length; j++){

var i = arr2[j][1];

for(var k = 0; k < arr1.length; k++){
var idx = arr1.indexOf(i);
if(idx === -1){
arr1.push(i);
}
}


}
return arr1;

}


When I try:

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 // I get 8 instead of 6


When I try:

updateInventory([[21, "Bowling Ball"], [2, "Dirty Sock"],
[1, "Hair Pin"], [5, "Microphone"]], [[2, "Hair Pin"],
[3, "Half-Eaten Apple"], [67, "Bowling Ball"],
[7, "Toothpaste"]])


I get:
enter image description here

When I should get:

[[88, "Bowling Ball"], [2, "Dirty Sock"], [3, "Hair Pin"],
[3, "Half-Eaten Apple"], [5, "Microphone"], [7, "Toothpaste"]]


I believe this is where my problem is...

for(var j = 0; j < arr2.length; j++){

var i = arr2[j][1];

for(var k = 0; k < arr1.length; k++){
var idx = arr1.indexOf(i);
if(idx === -1){
arr1.push(i);
}
}


}


cause it's sort of working. But can anyone help with the alphabetical sorting part too? Thanks in advance!

Answer

Try this

function updateInventory(arr1, arr2) {
  for (var x = 0; x < arr1.length; x++) {

    for (var y = 0; y < arr2.length; y++) {

      if (arr1[x][1] === arr2[y][1]) {
        arr1[x][0] = arr2[y][0] + arr1[x][0];
      }
    }
  }

  for (var j = 0; j < arr2.length; j++) {

    var i = arr2[j][1];
    var found = 0;

    for (var k = 0; k < arr1.length; k++) {
      if (arr1[k][1] === arr2[j][1]){
        found = 1;}
    }
    if (found == 0)
      arr1.push(arr2[j]);
  }
  arr1.sort(compareSecondColumn);
  return arr1;

}

for sorting

function compareSecondColumn(a, b) {
    if (a[1] === b[1]) {
        return 0;
    }
    else {
        return (a[1] < b[1]) ? -1 : 1;
    }
}