Array de objetos, sort, order, by key

 

How to sort alphabetically an array of objects by key in JavaScript

To sort an array of objects by some key, you will need a valid structure in your array, obviously an array of objects can only have objects with at least one key (the one that you want to sort). In this example, we’ll have the MyData variable that has the following structure: 

var MyData = [
{ id : 1, name: «Angel Miguel», city: «Nex Mexico» },
{ id : 2, name: «Michael Rogers», city: «Bogotá» },
{ id : 3, name: «Steve Rogers», city: «New York» },
{ id : 4, name: «Ángel José», city: «Bucaramanga»},
{ id : 5, name: «Carlos Delgado», city: «Nex Mexico» },
{ id : 6, name: «Jhonny Zapata», city: «Zacatecas» },
{ id : 7, name: «Bruce Wayne», city: «Gotham» },
{ id : 8, name: «Speedy Gonzales»,city: «Nex Mexico» }
];

Create a custom sort Function

you can simply use:

/**
Function to sort alphabetically an array of objects by some specific key.

@param {String} property Key of the object to sort.
/

function dynamicSort(property) {
var sortOrder = 1;

if(property[0] === «-«) {
sortOrder = 1;
property = property.substr(1);
}

return function (a,b) {
if(sortOrder == 1){
return b[property].localeCompare(a[property]);
}else{
return a[property].localeCompare(b[property]);
}
}
}

 

 Sort by key in ascending order

// Sort the MyData array with the custom function
// that sorts alphabetically by the name key
MyData.sort(dynamicSort(«name»));
// Display data with new order !
console.log(MyData);

object with the new order:

[
{ «id»:4, «name»: «Ángel José», «city»:«Bucaramanga» },
{ «id»:1, «name»: «Angel Miguel», «city»:«Nex Mexico» },
{ «id»:7, «name»: «Bruce Wayne», «city»:«Gotham» },
{ «id»:5, «name»: «Carlos Delgado», «city»:«Nex Mexico» },
{ «id»:6, «name»: «Jhonny Zapata», «city»:«Zacatecas» },
{ «id»:2, «name»: «Michael Rogers», «city»:«Bogotá» },
{ «id»:8, «name»: «Speedy Gonzales»,«city»:«Nex Mexico» },
{ «id»:3, «name»: «Steve Rogers», «city»:«New York» }
]

Sort by key in descending order

// Sort the MyData array with the custom function
// that sorts alphabetically in descending order by the name key
MyData.sort(dynamicSort(«-name»));
// Display data with new order !
console.log(MyData);

This would output:

[
{ «id» :3, «name» : «Steve Rogers», «city»:«New York» },
{ «id» :8, «name» : «Speedy Gonzales», «city»:«Nex Mexico» },
{ «id» :2, «name» : «Michael Rogers», «city»:«Bogotá» },
{ «id» :6, «name» : «Jhonny Zapata», «city»:«Zacatecas» },
{ «id» :5, «name» : «Carlos Delgado», «city»:«Nex Mexico» },
{ «id» :7, «name» : «Bruce Wayne», «city»:«Gotham» },
{ «id» :1, «name» : «Angel Miguel», «city»:«Nex Mexico» },
{ «id» :4, «name» : «Ángel José», «city»:«Bucaramanga»}
]

Continua leyendo «Array de objetos, sort, order, by key»

Entradas relacionadas

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *