I need to create an array with the names of the users but ordered by their ids. What I did was isolate in a new array with a map to the names and ids, and then try to use sort(function(a,b)) but it doesn't work for me.
const users = [
{ dni: '86620855', id: 4, nombres: 'Pedro Aguirre'},
{ dni: '7317855K', id: 1, nombres: 'Juan Carlos'},
{ dni: '73826497', id: 6, nombres: 'Esteban Herrera'},
{ dni: '88587715', id: 3, nombres: 'Ricardo Lucas'},
{ dni: '94020190', id: 5, nombres: 'Mauricio Hernandez'},
{ dni: '99804238', id: 2, nombres: 'Silena Roz' }
]
const arreglo2= users.map(item => (
{id: item.id, nombres: item.nombres}
))
const arreglotodo= arreglo2.sort(function(a,b){
return a.nombres -b.nombres
})
console.log(arreglotodo)
I can't figure out how to do it anymore. Is there any simple way to do it?
You have a very clear idea, however I don't understand why you are
sort
using the name field, if what you want to do is order byid
: I need to create an array with the names of the users but ordered by their ids.What you need to do is use the field
id
in the compare function.For example, this sorts the list
users
in ascending order using the fieldid
:I hope this helps you solve the problem.