Sort array by firstname (alphabetically) in Javascript

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

    In case we are sorting names or something with special characters, like ñ or áéíóú (commons in Spanish) we could use the params locales (es for spanish in this case ) and options like this:

    let user = [{'firstname': 'Az'},{'firstname': 'Áb'},{'firstname':'ay'},{'firstname': 'Ña'},{'firstname': 'Nz'},{'firstname': 'ny'}];
    
    
    user.sort((a, b) => a.firstname.localeCompare(b.firstname, 'es', {sensitivity: 'base'}))
    
    
    console.log(user)

    The oficial locale options could be found here in iana, es (spanish), de (German), fr (French). About sensitivity base means:

    Only strings that differ in base letters compare as unequal. Examples: a ≠ b, a = á, a = A.

提交回复
热议问题