Inventory Update sorting 2D array

Tell us what’s happening:
Hello,
I’m working on that chalnge
And first question which I’m trying to solve how to sort 2D array by the sekond parametr arr[1]
by the first parameter no problem but how to do it by the second
How correctly to do it?

Your code so far

function updateInventory(arr1, arr2) {
    
    arr2.sort(function(a, b){

    //how to sort arry by the a[1] not by the a[0]???   
      return a[0] - b[0];
      
    });
    return arr2;
}

// Example inventory lists
var curInv = [
    [21, "Bowling Ball"],
    [2, "Dirty Sock"],
    [1, "Hair Pin"],
    [5, "Microphone"]
];

var newInv = [
    [2, "Hair Pin"],
    [15, "Half-Eaten Apple"],
    [9, "Bowling Ball"],
    [6, "Toothpaste"]
];

updateInventory(curInv, newInv);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Safari/537.36.

Link to the challenge:
https://www.freecodecamp.org/challenges/inventory-update

Have you tried just replacing the 0 with 1?

Yes I try it
when a[0] -b[0]
it ok and it sorting by the integer values
but when I change a[1] - b[1] here is not any sorting by the characters :frowning:

The problem isn’t with the fact that it’s the second value in an array, it’s that you are trying to subtract one string from another string.

1 Like

Hi,
thanks for advice but I don’t catch it :flushed:
but I have solved it with arr2[i].reverse();

here is my code

<p>
function updateInventory(arr1, arr2) {   
   
   
    for(var i = 0; i < arr2.length; i++){
       arr2[i].reverse();      
    }
    arr2.sort();
    for(var i = 0; i < arr2.length; i++){
        arr2[i].reverse();
    }

  console.log(arr2);

  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);
</p>

Sorry it may stupy mistake I don’t mention that I need sort alphabetically

Sorry :face_with_thermometer:

Well either way, the following code you wrote:

function updateInventory(arr1, arr2) {   
    for(var i = 0; i < arr2.length; i++){
       arr2[i].reverse();      
    }
    arr2.sort();
    for(var i = 0; i < arr2.length; i++){
        arr2[i].reverse();
    }
  console.log(arr2);
}

can be accomplished with the following simple code and not get into reversing arrays:

function updateInventory(arr1, arr2) {
  arr2.sort((a, b) => a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0);
  console.log(arr2);
}
1 Like

Thank you very much for advice :slight_smile: