Sort array by firstname (alphabetically) in Javascript

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

    A generalized function can be written like below

        function getSortedData(data, prop, isAsc) {
            return data.sort((a, b) => (a[prop] < b[prop] ? -1 : 1) * (isAsc ? 1 : -1));
       }
    

    you can pass the below parameters

    1. The data which you want to sort
    2. The property in the data by it should be sorted
    3. The last parameter is of boolean type. It checks if you want to sort by ascending or by descending

提交回复
热议问题