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?
CodePudding user response:
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 ]
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
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);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Additionally I'd encourage you to go through here as well