Skip to content

Instantly share code, notes, and snippets.

@viniceosm
Created August 1, 2018 17:37
Show Gist options
  • Save viniceosm/cf5436090feee19baeb35f0a0ff87963 to your computer and use it in GitHub Desktop.
Save viniceosm/cf5436090feee19baeb35f0a0ff87963 to your computer and use it in GitHub Desktop.
order by [nome or idade] array of objects js
let pessoas = [
{
nome: 'Naiara',
idade: 18
},
{
nome: 'Alice',
idade: 24
},
{
nome: 'Barbara',
idade: 21
}
];
let sorteadoPorNome = sortearPorNome(pessoas, -1);
let sorteadoPorIdade = sortearPorIdade(pessoas, -1);
console.log('nome:', sorteadoPorNome);
console.log('idade:', sorteadoPorIdade);
function sortearPorNome(array, order) {
let byName = array.slice(0);
return byName.sort(function (a, b){
let x = a.nome.toLowerCase();
let y = b.nome.toLowerCase();
if (order == 1)
return x < y ? -1 : x > y ? 1 : 0;
return x > y ? -1 : x < y ? 1 : 0;
});
}
function sortearPorIdade(array, order) {
let byIdade = array.slice(0);
return byIdade.sort(function (a, b) {
let x = a.idade;
let y = b.idade;
if (order == 1)
return x - y;
return y - x;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment