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
Pushed the top answers into a prototype to sort by key.
Array.prototype.alphaSortByKey= function (key) {
this.sort(function (a, b) {
if (a[key] < b[key])
return -1;
if (a[key] > b[key])
return 1;
return 0;
});
return this;
};
You can use something similar, to get rid of case sensitive
users.sort(function(a, b){
//compare two values
if(a.firstname.toLowerCase() < b.firstname.toLowerCase()) return -1;
if(a.firstname.toLowerCase() > b.firstname.toLowerCase()) return 1;
return 0;
})
Inspired from this answer,
users.sort((a,b) => (a.firstname - b.firstname));
Shortest possible code with ES6!
users.sort((a, b) => a.firstname.localeCompare(b.firstname))
String.prototype.localeCompare() basic support is universal!
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: "<null>",
email: "user@domain.com",
firstname: 'Anna',
id: 318,
"last_avatar": "<null>",
"last_message": "<null>",
lastname: 'Nickson',
nickname: 'anny'
},
{
bio: "<null>",
email: "user@domain.com",
firstname: 'Senad',
id: 318,
"last_avatar": "<null>",
"last_message": "<null>",
lastname: 'Nickson',
nickname: 'anny'
},
{
bio: "<null>",
email: "user@domain.com",
firstname: 'Muhamed',
id: 318,
"last_avatar": "<null>",
"last_message": "<null>",
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;
});
My implementation, works great in older ES versions:
sortObject = function(data) {
var keys = Object.keys(data);
var result = {};
keys.sort();
for(var i = 0; i < keys.length; i++) {
var key = keys[i];
result[key] = data[key];
}
return result;
};