<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<button onclick="myFunction()">Try it</button>
<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;
function myFunction() {
points.sort(function(a, b) {returns a - b});
document.getElementById("demo").innerHTML = points;
}
</script>
</body>
</html>
We looked at the example sentence after seeing the w3schools tutorial that the string works exactly when using the sort() method, but it does not work normally when it is in numeric form. In the document, you can use the trick as shown above to show normal movements.
points.sort(function(a, b) {returns a - b});
I don't understand this part. So, are we going to compare and sort using the value minus [40, 100] minus -60, minus [1, 5] minus -4 and [25, 10] minus 15?
I thought it works like above, but I wonder how the last 25 and 10 are aligned.
javascript sorting array
var points = [40, 100, 1, 5, 25, 10]
points.sort();
// // Array [ 1, 10, 100, 25, 40, 5 ]
points.sort(function(a, b) { return a - b });
// // Array [ 1, 5, 10, 25, 40, 100 ]
For array.sort(fn)
, change the index to forward a if fn(a, b)
returns less than 0, leave 0 and forward b if greater than 0.
In the above source, if a - b is less than 0, then a is forward, if it is 0, then b is forward, right?
Please refer to the following link: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
© 2024 OneMinuteCode. All rights reserved.