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
in simply words you can use this method
users.sort(function(a,b){return a.firstname < b.firstname ? -1 : 1});
You can use this for objects
transform(array: any[], field: string): any[] {
return array.sort((a, b) => a[field].toLowerCase() !== b[field].toLowerCase() ? a[field].toLowerCase() < b[field].toLowerCase() ? -1 : 1 : 0);}
You can use the in-built array method - sort
. This method takes a callback method as a param
// custom sort function to be passed as param/callback to the Array's sort method
function myCustomSort(a, b) {
return (a.toLowerCase() > b.toLowerCase()) ? 1 : -1;
}
// Actual method to be called by entity that needs sorting feature
function sortStrings() {
var op = Array.prototype.sort.call(arguments, myCustomSort);
}
// Testing the implementation
var sortedArray = sortStrings("Burger", "Mayo1", "Pizza", "boxes", "Apples", "Mayo");
console.log(sortedArray); //["Apples", "boxes", "Burger", "Mayo", "Mayo1", "Pizza"]
Key Points to be noted for understanding this code.
myCustomSort
, should return +1 or -1 for each element pair(from the input array) comparison.toLowerCase()
/toUpperCase()
in the custom sorting callback method so that case difference does not affect the correctness of the sorting process.I hope this is clear enough explanation. Feel free to comment if you think, more info is needed.
Cheers!
Nice little ES6 one liner:
users.sort((a, b) => a.firstname !== b.firstname ? a.firstname < b.firstname ? -1 : 1 : 0);
A more compact notation:
user.sort(function(a, b){
return a.firstname === b.firstname ? 0 : a.firstname < b.firstname ? -1 : 1;
})