Skip to content

Instantly share code, notes, and snippets.

@guidani
Created September 7, 2022 13:57
Show Gist options
  • Save guidani/02fa0b8cecb52e048689567b14260055 to your computer and use it in GitHub Desktop.
Save guidani/02fa0b8cecb52e048689567b14260055 to your computer and use it in GitHub Desktop.
Funções para ordenação de uma array de objetos em javascript utilizando um método sort(). Pode ser adaptado para outras situações
let pessoas = [{
nome: "Guilherme",
id: 4
},
{
nome: "Daniel",
id: 2
},
{
nome: "Rick",
id: 1
},
{
nome: "Morty",
id: 3,
}
]
function ordByName(arr){
let ordenado = arr.sort(function(a,b) {
return a.nome < b.nome ? -1 : a.nome > b.nome ? 1 : 0;
});
return ordenado
}
function ordById(arr){
let ordenado = arr.sort(function(a,b) {
return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
});
return ordenado
}
console.log(ordById(pessoas))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment