# Why sort(a,b => a[1]-b[1]) won't work but long version of sort works

Tell us what’s happening:
to sort by alphabetical order of Array I’ve tried to use
arr1.sort((a,b) => a-b) ) which works with numbers
I was curious to why would not work with the Alphabetics.

``````  **Your code so far**
``````
``````
function updateInventory(arr1, arr2) {
const arr1Inv = arr1.map(el => el[1]);
const arr2Inv = arr2.map(el => el[1]);
for (let i=0; i<arr2Inv.length; i++) {
if ( arr1Inv.includes(arr2Inv[i]) ) {
let index = arr1Inv.indexOf(arr2Inv[i]);
arr1[index][0] += arr2[i][0];
} else {
arr1.push(arr2[i])
}
}
arr1.sort(function(a, b) {
if (a[1] > b[1]) {
return 1;
}
if (a[1] < b[1]) {
return -1;
}
return 0;
});
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"]
];

console.log(updateInventory(curInv, newInv));
``````
``````  **Your browser information:**
``````

User Agent is: `Mozilla/5.0 (Macintosh; Intel Mac OS X 11_1_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.128 Safari/537.36`.

Challenge: Inventory Update

Link to the challenge:

When in doubt, try a small example

``````console.log("a" - "b");
``````

The callback function for sort has to return a number, and the array is sorted based on if that number is positive, negative, or zero.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

`NaN` is not a valid number ( in the name Not a Number), so you won’t get the results you want.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.