Sort array by firstname (alphabetically) in Javascript

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

    in simply words you can use this method

    users.sort(function(a,b){return a.firstname < b.firstname ? -1 : 1});
    
    0 讨论(0)
  • 2020-11-22 12:26

    You can use this for objects

    transform(array: any[], field: string): any[] {
    return array.sort((a, b) => a[field].toLowerCase() !== b[field].toLowerCase() ? a[field].toLowerCase() < b[field].toLowerCase() ? -1 : 1 : 0);}
    
    0 讨论(0)
  • 2020-11-22 12:29

    You can use the in-built array method - sort. This method takes a callback method as a param

    
    
        // custom sort function to be passed as param/callback to the Array's sort method
        function myCustomSort(a, b) {
            return (a.toLowerCase() > b.toLowerCase()) ? 1 : -1;
        }
    
        // Actual method to be called by entity that needs sorting feature
        function sortStrings() {
            var op = Array.prototype.sort.call(arguments, myCustomSort);
        }
    
        // Testing the implementation
        var sortedArray = sortStrings("Burger", "Mayo1", "Pizza", "boxes", "Apples", "Mayo");
        console.log(sortedArray); //["Apples", "boxes", "Burger", "Mayo", "Mayo1", "Pizza"]
    
    
    

    Key Points to be noted for understanding this code.

    1. The custom method, in this case, myCustomSort, should return +1 or -1 for each element pair(from the input array) comparison.
    2. Use toLowerCase()/toUpperCase() in the custom sorting callback method so that case difference does not affect the correctness of the sorting process.

    I hope this is clear enough explanation. Feel free to comment if you think, more info is needed.

    Cheers!

    0 讨论(0)
  • 2020-11-22 12:32

    Nice little ES6 one liner:

    users.sort((a, b) => a.firstname !== b.firstname ? a.firstname < b.firstname ? -1 : 1 : 0);
    
    0 讨论(0)
  • 2020-11-22 12:32

    A more compact notation:

    user.sort(function(a, b){
        return a.firstname === b.firstname ? 0 : a.firstname < b.firstname ? -1 : 1;
    })
    
    0 讨论(0)
提交回复
热议问题