Sort array by firstname (alphabetically) in Javascript

前端 未结 23 3044
天命终不由人
天命终不由人 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:14

    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))
    

提交回复
热议问题