0

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?

1
  • How do you know what a and b are? You’re not even looking at them. Commented May 8, 2022 at 5:27

2 Answers 2

2

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.