I am trying to sort a JSON by a field alphabetically but I am not successful.
The code of the function that I was testing is this, but in the end it does not order the JSON:
const ordenar = function () {
let array = [
{Materia: 'DERECHO CONSTITUCIONAL', SubMateria: 'ACCION DE AMPARO'},
{Materia: 'COMERCIAL', SubMateria: 'OBLIGACION DE DAR SUMA DE DINERO'},
{Materia: 'CONTENCIOSO ADMINISTRATIVO', SubMateria: 'REVISION JUDICIAL'},
{Materia: 'FAMILIA TUTELAR', SubMateria: 'VIOLENCIA CONTRA LAS MUJERES'},
{Materia: 'CIVIL', SubMateria: 'OBLIGACION DE DAR SUMA DE DINERO'},
{Materia: 'FAMILIA CIVIL', SubMateria: 'DIVORCIO POR CAUSAL'},
{Materia: 'LABORAL', SubMateria: 'NULIDAD DE RESOLUCION ADMINISTRATIVA'},
]
console.log("array inicial : ", array)
var newArray=array.sort((a, b)=> {
var textA = a.Materia;
var textB = b.Materia;
return textA - textB;
});
console.log("array salida : ", newArray)
}
you can use the Sort method making a direct comparison between the strings, example:
Some considerations:
What you want to order is an array of objects, not an object, not a json.
.sort
alters the array it sorts, so there's no need to store it in another variable..sort
by default it has an unwanted behavior with uppercase, lowercase and non-english characters:It can be verified that the variants do not solve the problem.
What can be done is to use .localCompare using the second parameter which is the locals, in the case of Spanish it is 'es'. In addition, it can be indicated that we only consider the base, the base of "á" is equal to "a" and "A". Example: