I got an array (see below for one object in the array) that I need to sort by firstname using JavaScript. How can I do it?
var user = {
bio: null,
emai
Basically you can sort arrays with method sort, but if you want to sort objects then you have to pass function to sort method of array, so I will give you an example using your array
user = [{
bio: "",
email: "user@domain.com",
firstname: 'Anna',
id: 318,
"last_avatar": "",
"last_message": "",
lastname: 'Nickson',
nickname: 'anny'
},
{
bio: "",
email: "user@domain.com",
firstname: 'Senad',
id: 318,
"last_avatar": "",
"last_message": "",
lastname: 'Nickson',
nickname: 'anny'
},
{
bio: "",
email: "user@domain.com",
firstname: 'Muhamed',
id: 318,
"last_avatar": "",
"last_message": "",
lastname: 'Nickson',
nickname: 'anny'
}];
var ar = user.sort(function(a, b)
{
var nA = a.firstname.toLowerCase();
var nB = b.firstname.toLowerCase();
if(nA < nB)
return -1;
else if(nA > nB)
return 1;
return 0;
});