Sort array by firstname (alphabetically) in Javascript

前端 未结 23 2878
天命终不由人
天命终不由人 2020-11-22 11:46

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         


        
23条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 12:07

    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

提交回复
热议问题