Skip to content

Instantly share code, notes, and snippets.

@abrkof
Forked from fmagrosoto/OrdenarJSONconJS.html
Created April 11, 2019 13:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abrkof/135d0dfb67ba19f22d3f4e3cd1ccb83a to your computer and use it in GitHub Desktop.
Save abrkof/135d0dfb67ba19f22d3f4e3cd1ccb83a to your computer and use it in GitHub Desktop.
Ordenar JSON por medio del valor de una de sus propiedades. La propiedad es pasada como parámetro.
// Creamos el JSON
var elJSON = [
{nombre: 'Fernando', num: 89875, sexo: 'masculino'},
{nombre: 'Octavio', num: 76867, sexo: 'masculino'},
{nombre: 'Sandra', num: 45345, sexo: 'femenino'},
{nombre: 'Alvaro', num: 23, sexo: 'masculino'},
{nombre: 'Roxana', num: 4545, sexo: 'femenino'},
{nombre: 'Benito', num: 234, sexo: 'masculino'},
{nombre: 'Alejandra', num: 8900, sexo: 'femenino'},
{nombre: 'Carlos', num: 5654, sexo: 'masculino'}
];
// Pintamos en pantalla el JSON normal
var jsonN = document.getElementById('jsonN');
jsonN.textContent = JSON.stringify(elJSON);
console.log(JSON.stringify(elJSON));
/**
* Ordenar JSON por medio del valor de una de sus propiedades
* @author Fernando Magrosoto V. (@fmagrosoto)
* @see https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Array/sort
* @example sortJSON(json, propiedad, el orden)
* @licence MIT
* @version 1.0
* @copyleft 2016 - Fernando Magrosoto V.
*
*/
function sortJSON(data, key, orden) {
return data.sort(function (a, b) {
var x = a[key],
y = b[key];
if (orden === 'asc') {
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}
if (orden === 'desc') {
return ((x > y) ? -1 : ((x < y) ? 1 : 0));
}
});
}
// Ordenamos el json.
// Ojo, hay que incluir como parámetro:
// El JSON origninal
// La propiedad que queremos ordenar
// El orden (asc | desc)
var oJSON = sortJSON(elJSON, 'num', 'asc');
// Ej. var oJSON = sortJSON(elJSON, 'nombre', 'asc');
// Ej. var oJSON = sortJSON(elJSON, 'sexo', 'desc');
// Pintamos en pantalla el JSON ordenado
console.log(JSON.stringify(oJSON));
var jsonO = document.getElementById('jsonO');
jsonO.textContent = JSON.stringify(oJSON);
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Ordena JSON</title>
<meta name="description" content="Ordenar un JSON en Javascript">
<meta name="author" content="Fernando Magrosoto V.">
<style>
body {
background-color: white;
color: rgb(51,51,51);
font-family: sans-serif;
font-size: 14px
}
footer {
font-size: 12px;
padding: 10px;
background-color: rgba(255,200,0,.1);
border: 1px rgba(200,200,0,.25) solid;
}
</style>
</head>
<body>
<h1>Ordenar JSON con javascript</h1>
<hr>
<div id="jsonN"></div>
<hr>
<div id="jsonO"></div>
<hr>
<footer>Ver la consola para más detalles.</footer>
<script src="ordenarJSON.js"></script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment