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

128
Views
Outputting same value for two separate sorting functions

Hey doing drills on sorting and I found something that I don't fully understand.

let numbers = [1,3,2,5,4];
let sortedHighesttoLowest = numbers.sort((a, b)=> b-a);
let sortedLowesttoHighest = numbers.sort((a, b)=> a-b);

console.log(sortedHighesttoLowest);
console.log(sortedLowesttoHighest);

output: 
[ 1, 2, 3, 4, 5 ]
[ 1, 2, 3, 4, 5 ]

how come this outputs only the last function's value twice even though I assigned them to two separate variable?

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

0

Arrays are passed by reference. So when you assign to your variable a sorted array and then you sort again, the first variable will also be affected. You can use spread operator to avoid this.

let numbers = [1,3,2,5,4];
let sortedHighesttoLowest = [...numbers.sort((a, b)=> b-a)];
let sortedLowesttoHighest = [...numbers.sort((a, b)=> a-b)];

console.log(sortedHighesttoLowest);
console.log(sortedLowesttoHighest);

//output: 
//[ 1, 2, 3, 4, 5 ]
//[ 1, 2, 3, 4, 5 ]

about 4 years ago · Juan Pablo Isaza Report

0

The comparator function works little different than some traditional languages that you might be used to.

In js, the return value of comparator is -1, 0 and 1. Although in lot of cases you can get away with using - minus operator.

Having said that, you're passing array as reference here which is causing the problem.

Try running this:

let numbers = [1,3,2,5,4];
let sortedHighesttoLowest = numbers.sort((a, b)=> a - b);
console.log(sortedHighesttoLowest);

let sortedLowesttoHighest = numbers.sort((a, b)=> b - a);
console.log(sortedLowesttoHighest);

Additionally I'd encourage you to go through here as well

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!