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
try
users.sort((a,b)=> (a.firstname>b.firstname)*2-1)
var users = [
{ firstname: "Kate", id: 318, /*...*/ },
{ firstname: "Anna", id: 319, /*...*/ },
{ firstname: "Cristine", id: 317, /*...*/ },
]
console.log(users.sort((a,b)=> (a.firstname>b.firstname)*2-1) );
Just for the record, if you want to have a named sort-function, the syntax is as follows:
let sortFunction = (a, b) => {
if(a.firstname < b.firstname) { return -1; }
if(a.firstname > b.firstname) { return 1; }
return 0;
})
users.sort(sortFunction)
Note that the following does NOT work:
users.sort(sortFunction(a,b))
I'm surprised no one mentioned Collators. You shouldn't use localeCompare
unless you have to as it has significantly worse performance.
const collator = new Intl.Collator('zh-CN', { // Chinese Simplified for example
numeric: true,
sensitivity: 'base',
});
function sortAsc(a, b) {
if (typeof a === 'string' && typeof b === 'string') {
return collator.compare(b, a)
}
return b - a;
}
function sortDesc(a, b) {
if (typeof a === 'string' && typeof b === 'string') {
return collator.compare(a, b);
}
return a - b;
}
also for both asec and desc sort, u can use this : suppose we have a variable SortType that specify ascending sort or descending sort you want:
users.sort(function(a,b){
return sortType==="asc"? a.firstName.localeCompare( b.firstName): -( a.firstName.localeCompare( b.firstName));
})
Suppose you have an array users
. You may use users.sort
and pass a function that takes two arguments and compare them (comparator)
It should return
In our case if two elements are a
and b
we want to compare a.firstname
and b.firstname
Example:
users.sort(function(a, b){
if(a.firstname < b.firstname) { return -1; }
if(a.firstname > b.firstname) { return 1; }
return 0;
})
This code is going to work with any type.
Note that in "real life"™ you often want to ignore case, correctly sort diacritics, weird symbols like ß, etc when you compare strings, so you may want to use localeCompare
. See other answers for clarity.
A generalized function can be written like below
function getSortedData(data, prop, isAsc) {
return data.sort((a, b) => (a[prop] < b[prop] ? -1 : 1) * (isAsc ? 1 : -1));
}
you can pass the below parameters