Sort array by firstname (alphabetically) in Javascript

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

    Pushed the top answers into a prototype to sort by key.

    Array.prototype.alphaSortByKey= function (key) {
        this.sort(function (a, b) {
            if (a[key] < b[key])
                return -1;
            if (a[key] > b[key])
                return 1;
            return 0;
        });
        return this;
    };
    

提交回复
热议问题