Home > Enterprise >  Why does the sort() method does't work as expected with an array of strings?
Why does the sort() method does't work as expected with an array of strings?

Time:05-08

I'm experimenting with the sort() method in JavaScript. The documentation says the return value should be > 0 to sort b before a. I have the following code to reverse an array of strings, and have the return value as a positive integer, which I think should sort the array in the reverse order:

let nums = ["x", "y", "z"];
nums.sort((a, b) => 1); // returning a positive number to sort b before a
console.log(nums)

However, when I execute the code, the output is:

[ 'x', 'y', 'z' ] // not reversed at all

But the code does give me the expected value - [ 'z', 'y', 'x' ] - when I set the return value to a negative number. Is there an explanation for this? Am I doing something wrong?

CodePudding user response:

Here you are not conditionally check out a and b which is greater or lesser. Returning 1 will evaluate first parameter from sort((a, b) is greater. Which returns you exact same array.

You better compare those to value inside sort callback function and depending on value return 1 or -1.

This will result ascending order.

let nums = ["x", "y", "z"];
nums.sort((a, b) => a > b ? 1 : -1);
console.log(nums)

Toggle return value to get descending order.

let nums = ["x", "y", "z"];
nums.sort((a, b) => a > b ? -1 : 1);
console.log(nums)

CodePudding user response:

That happens because the callback of sort method, takes two params but they do not correspond as one would think to first second third...etc... elements but on the contrary, a is the second element, b is the first one, so when it says that a number greater than 1 places b ahead of a that's what it does:

const nums = ['x', 'y', 'z'];

nums.sort((a, b) => {
  console.log(a,b)  // yx -zy
});

  • Related