Sort array by firstname (alphabetically) in Javascript

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

    Suppose you have an array users. You may use users.sort and pass a function that takes two arguments and compare them (comparator)

    It should return

    • something negative if first argument is less than second (should be placed before the second in resulting array)
    • something positive if first argument is greater (should be placed after second one)
    • 0 if those two elements are equal.

    In our case if two elements are a and b we want to compare a.firstname and b.firstname

    Example:

    users.sort(function(a, b){
        if(a.firstname < b.firstname) { return -1; }
        if(a.firstname > b.firstname) { return 1; }
        return 0;
    })
    

    This code is going to work with any type.

    Note that in "real life"™ you often want to ignore case, correctly sort diacritics, weird symbols like ß, etc when you compare strings, so you may want to use localeCompare. See other answers for clarity.

提交回复
热议问题