How to sort strings in JavaScript

后端 未结 12 2182
生来不讨喜
生来不讨喜 2020-11-22 13:20

I have a list of objects I wish to sort based on a field attr of type string. I tried using -

list.sort(function (a, b) {
    retur         


        
12条回答
  •  轮回少年
    2020-11-22 13:43

    Answer (in Modern ECMAScript)

    list.sort((a, b) => (a.attr > b.attr) - (a.attr < b.attr))
    

    Or

    list.sort((a, b) => +(a.attr > b.attr) || -(a.attr < b.attr))
    

    Description

    Casting a boolean value to a number yields the following:

    • true -> 1
    • false -> 0

    Consider three possible patterns:

    • x is larger than y: (x > y) - (y < x) -> 1 - 0 -> 1
    • x is equal to y: (x > y) - (y < x) -> 0 - 0 -> 0
    • x is smaller than y: (x > y) - (y < x) -> 0 - 1 -> -1

    (Alternative)

    • x is larger than y: +(x > y) || -(x < y) -> 1 || 0 -> 1
    • x is equal to y: +(x > y) || -(x < y) -> 0 || 0 -> 0
    • x is smaller than y: +(x > y) || -(x < y) -> 0 || -1 -> -1

    So these logics are equivalent to typical sort comparator functions.

    if (x == y) {
        return 0;
    }
    return x > y ? 1 : -1;
    

提交回复
热议问题