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