Sort array by firstname (alphabetically) in Javascript

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

    I'm surprised no one mentioned Collators. You shouldn't use localeCompare unless you have to as it has significantly worse performance.

    const collator = new Intl.Collator('zh-CN', { // Chinese Simplified for example
      numeric: true,
      sensitivity: 'base',
    });
    
    function sortAsc(a, b) {
      if (typeof a === 'string' && typeof b === 'string') {
        return collator.compare(b, a)
      }
    
      return b - a;
    }
    
    function sortDesc(a, b) {
      if (typeof a === 'string' && typeof b === 'string') {
        return collator.compare(a, b);
      }
    
      return a - b;
    }
    

提交回复
热议问题