Created
November 10, 2017 19:37
-
-
Save fredyfx/2d6b36a6fea98578ce2e4a40f55df38e to your computer and use it in GitHub Desktop.
Código extraído de: https://www.w3schools.com/js/tryit.asp?filename=tryjs_array_sort_object2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<body> | |
<h2>JavaScript Array Sort</h2> | |
<p>Click the buttons to sort car objects on type.</p> | |
<button onclick="myFunction()">Sort</button> | |
<p id="demo"></p> | |
<script> | |
var cars = [ | |
{type:"Volvo", year:2016}, | |
{type:"Saab", year:2001}, | |
{type:"BMW", year:2010}] | |
displayCars(); | |
function myFunction() { | |
cars.sort(function(a, b){ | |
var x = a.type.toLowerCase(); | |
var y = b.type.toLowerCase(); | |
if (x < y) {return -1;} | |
if (x > y) {return 1;} | |
return 0; | |
}); | |
displayCars(); | |
} | |
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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment