Home  >  Q&A  >  body text

javascript - js how to arrange people's names in alphabetical order

Now we need to sort the personnel list in alphabetical order. The backend currently does not have this function. I ask the front desk to write it and ask for advice. Thank you!!

滿天的星座滿天的星座2712 days ago1213

reply all(6)I'll reply

  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-19 10:43:37

    sort() 方法用于对数组的元素进行排序。arrayObject.sort(sortby)

    Just use the sort() method of the array. The default rule is to sort the elements in the array in alphabetical order.

    reply
    0
  • 迷茫

    迷茫2017-05-19 10:43:37

    Put the list of personnel into the array and use array.sort() to sort it alphabetically.
    Please refer to: https://developer.mozilla.org...

    reply
    0
  • 阿神

    阿神2017-05-19 10:43:37

    var arr = ['ac','ab','bb','bc','aa'];
    arr.sort();
    // ["aa", "ab", "ac", "bb", "bc"]

    The default sorting of arrays is dictionary order. If the person is Chinese, then the Chinese needs to be converted into Pinyin first and then sorted.

    The method of converting to pinyin can be found online. The code is generally long, so I won’t paste it.

    reply
    0
  • 黄舟

    黄舟2017-05-19 10:43:37

    Let me be clear, are they all Chinese, or do they have English names? And if there are English names, are the Chinese mixed or separated?

    To make it simple, find a Chinese to Pinyin conversion library on github, convert the last name to Pinyin and then sort by the first letter.

    reply
    0
  • 迷茫

    迷茫2017-05-19 10:43:37

    ['小二','小弟','大哥'].sort((a, b) => a.localeCompare(b))

    reply
    0
  • 阿神

    阿神2017-05-19 10:43:37

    It is recommended to extract the first letters of the names and store them in the array to be sorted;
    Then use sort to sort.

    As for the code provided upstairs, there is a problem;

    console.log(['王', '啊','小','发','大哥'].sort((a, b) => a.localeCompare(b)));
    // -> 发 啊 大哥 小 王

    Under normal circumstances, the output should be: Ah, big brother sent....

    reply
    0
  • Cancelreply