Exécuter
❯
Exécuter le code
Ctrl+Alt+R
Enregistrer le code
Ctrl+Alt+A
Changer d'orientation
Ctrl+Alt+O
Changer de thème
Ctrl+Alt+D
<!DOCTYPE html> <html> <body> <h1>Tableaux JavaScript</h1> <h2>La méthode sort()</h2> <p>Cliquez sur les boutons pour trier les objets voiture par type.</p> <button onclick="myFunction()">Trier</button> <p id="demo"></p> <script> const cars = [ {type:"Volvo", year:2016}, {type:"Saab", year:2001}, {type:"BMW", year:2010} ]; displayCars(); function myFunction() { cars.sort(function(a, b){ let x = a.type.toLowerCase(); let y = b.type.toLowerCase(); if (x < y) {return -1;} if (x > y) {return 1;} return 0; }); afficherVoitures(); } function displayCars() { document.getElementById("demo").innerHTML = cars[0].type + " " + cars[0].year + "<br>" + cars[1].type + " " + cars[1].year + "<br>" + cars[2].type + " " + cars[2].year; } </script> </body> </html>