Array Sort ordinamento




'Ordinamento di una matrice

'Il sort()metodo ordina una matrice alfabeticamente:


'Esempio

'var fruits = ["Banana", "Orange", "Apple", "Mango"];

'fruits.sort(); // Sorts the elements of fruits


https://www.w3schools.com/js/tryit.asp?filename=tryjs_array_sort

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array Sort</h2>

<p>The sort() method sorts an array alphabetically.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits;

function myFunction() {
fruits.sort();
document.getElementById("demo").innerHTML = fruits;
}
</script>

</body>
</html>


'Ordinamento numerico

'Per impostazione predefinita, la sort()funzione ordina i valori come stringhe .

'Funziona bene per le stringhe ("Apple" viene prima di "Banana").

'Tuttavia, se i numeri sono ordinati come stringhe, "25" e' maggiore di "100", perche' "2" e' maggiore di "1".

'Per questo motivo, il sort()metodo produrra' risultati errati durante l'ordinamento dei numeri.

'Puoi risolvere questo problema fornendo una funzione di confronto :

'Esempio

'var points = [40, 100, 1, 5, 25, 10];

'points.sort(function(a, b){return a - b});


https://www.w3schools.com/js/tryit.asp?filename=tryjs_array_sort2

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Array Sort</h2>

<p>Click the button to sort the array in ascending order.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
var points = [40, 100, 1, 5, 25, 10];
document.getElementById("demo").innerHTML = points;

function myFunction() {
points.sort(function(a, b){return a - b});
document.getElementById("demo").innerHTML = points;
}
</script>

</body>
</html>










( arraysortordinamento.html )- by Paolo Puglisi - Modifica del 17/12/2023