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
We can use localeCompare but need to check the keys as well for falsey values
The code below will not work if one entry has missing lname.
obj.sort((a, b) => a.lname.localeCompare(b.lname))
So we need to check for falsey value like below
let obj=[
{name:'john',lname:'doe',address:'Alaska'},
{name:'tom',lname:'hopes',address:'California'},
{name:'harry',address:'Texas'}
]
let field='lname';
console.log(obj.sort((a, b) => (a[field] || "").toString().localeCompare((b[field] || "").toString())));
OR
we can use lodash , its very simple. It will detect the returned values i.e whether number or string and do sorting accordingly .
import sortBy from 'lodash/sortBy';
sortBy(obj,'name')
https://lodash.com/docs/4.17.5#sortBy
for a two factors sort (name and lastname):
users.sort((a, b) => a.name.toLowerCase() < b.name.toLowerCase() ? -1 : a.name.toLowerCase() > b.name.toLowerCase() ? 1 : a.lastname.toLowerCase() < b.lastname.toLowerCase() ? -1 : a.lastname.toLowerCase() > b.lastname.toLowerCase() ? 1 : 0)
Something like this:
array.sort(function(a, b){
var nameA=a.name.toLowerCase(), nameB=b.name.toLowerCase();
if (nameA < nameB) //sort string ascending
return -1;
if (nameA > nameB)
return 1;
return 0; //default return value (no sorting)
});
If compared strings contain unicode characters you can use localeCompare function of String
class like the following:
users.sort(function(a,b){
return a.firstname.localeCompare(b.firstname);
})
In case we are sorting names or something with special characters, like ñ or áéíóú (commons in Spanish) we could use the params locales (es for spanish in this case ) and options like this:
let user = [{'firstname': 'Az'},{'firstname': 'Áb'},{'firstname':'ay'},{'firstname': 'Ña'},{'firstname': 'Nz'},{'firstname': 'ny'}];
user.sort((a, b) => a.firstname.localeCompare(b.firstname, 'es', {sensitivity: 'base'}))
console.log(user)
The oficial locale options could be found here in iana, es (spanish), de (German), fr (French). About sensitivity base means:
Only strings that differ in base letters compare as unequal. Examples: a ≠ b, a = á, a = A.
underscorejs offers the very nice _.sortBy function:
_.sortBy([{a:1},{a:3},{a:2}], "a")
or you can use a custom sort function:
_.sortBy([{a:"b"},{a:"c"},{a:"a"}], function(i) {return i.a.toLowerCase()})