Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

289
Views
Why does the sort() method does't work as expected with an array of strings?

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!