Created
September 7, 2022 13:57
-
-
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
This file contains 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
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