In my JavaScript code, I start with an array of numbers and then do the following:
- Sort it in ascending order;
- Ask the browser to display the array;
- Sort it in descending order;
- Ask the browser to display the array.
What the browser seems to do is sort the array in ascending order, then sort in descending order, then display the array (x2) – which doesn’t follow the order of the code. I would be most grateful is anyone can help explain the issue, thanks.
Here’s the code:
var numbersArray = [60, 50, 62, 58, 54, 54];
// For sorting in ascending order
function compareNumbers(num1, num2) {
if (num1 > num2) {
return 1;
} else if (num1 === num2) {
return 0;
} else {
return -1;
}
}
// For sorting in descending order
function compareNumbersDesc(num1, num2) {
if (num2 > num1) {
return 1;
} else if (num1 === num2) {
return 0;
} else {
return -1;
}
}
numbersArray.sort(compareNumbers);
console.log(numbersArray);
numbersArray.sort(compareNumbersDesc);
console.log(numbersArray);
The console displays:
[ 62, 60, 58, 54, 54, 50 ]
[ 62, 60, 58, 54, 54, 50 ]
But even stranger is if I simply refresh the page, the console now displays:
[ 50, 54, 54, 58, 60, 62 ]
[ 62, 60, 58, 54, 54, 50 ]
Does anyone know what’s going on? Thanks in advance!