[ACCEPTED]-Sort JavaScript array of Objects based on one of the object's properties-javascript
There are 2 basic ways:
var arr = [{name:"ABC"},{name:"BAC"},{name:"abc"},{name:"bac"}];
arr.sort(function(a,b){
var alc = a.name.toLowerCase(), blc = b.name.toLowerCase();
return alc > blc ? 1 : alc < blc ? -1 : 0;
});
or
arr.sort(function(a,b){
return a.name.toLowerCase().localeCompare(b.name.toLowerCase());
});
Be aware that the 9 2nd version ignore diacritics, so a
and à
will 8 be sorted as the same letter.
Now the problem 7 with both these ways is that they will not 6 sort uppercase ABC
before lowercase abc
, since 5 it will treat them as the same.
To fix that, you 4 will have to do it like this:
arr.sort(function(a,b){
var alc = a.name.toLowerCase(), blc = b.name.toLowerCase();
return alc > blc ? 1 : alc < blc ? -1 : a.name > b.name ? 1 : a.name < b.name ? -1 : 0;
});
Again here 3 you could choose to use localeCompare
instead if you 2 don't want diacritics to affect the sorting 1 like this:
arr.sort(function(a,b){
var lccomp = a.name.toLowerCase().localeCompare(b.name.toLowerCase());
return lccomp ? lccomp : a.name > b.name ? 1 : a.name < b.name ? -1 : 0;
});
You can read more about sort here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort
You can pass a custom sorting function to 3 the sort()
method of an array. The following will 2 do the trick and take your requirements 1 about capitalization into account.
objects.sort(function(o1, o2) {
var n1 = o1.name, n2 = o2.name, ni1 = n1.toLowerCase(), ni2 = n2.toLowerCase();
return ni1 === ni2 ? (n1 === n2 ? 0 : n1 > n2 ? 1 : -1) : (ni1 > ni2 ? 1 : -1);
});
Slightly modified from Sorting an array of objects,
yourobject.sort(function(a, b) {
var nameA = a.name, nameB = b.name
if (nameA < nameB) //Sort string ascending.
return -1
if (nameA > nameB)
return 1
return 0 //Default return value (no sorting).
})
0
objects.sort(function(c, d) {
return (
c['name'].toLowerCase() > d['name'].toLowerCase() ||
c['name'] > d['name']
) ? 1 : -1;
});
see there http://jsfiddle.net/p8Gny/1/
0
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.