How to sort an array of objects by multiple fields?

后端 未结 30 2842
北恋
北恋 2020-11-21 11:34

From this original question, how would I apply a sort on multiple fields?

Using this slightly adapted structure, how would I sort city (ascending) & then price (

30条回答
  •  无人及你
    2020-11-21 12:11

    I think this may be the easiest way to do it.

    https://coderwall.com/p/ebqhca/javascript-sort-by-two-fields

    It's really simple and I tried it with 3 different key value pairs and it worked great.

    Here is a simple example, look at the link for more details

    testSort(data) {
        return data.sort(
            a['nameOne'] > b['nameOne'] ? 1
            : b['nameOne'] > a['nameOne'] ? -1 : 0 ||
            a['date'] > b['date'] ||
            a['number'] - b['number']
        );
    }
    

提交回复
热议问题