How to sort an array of objects by multiple fields?

后端 未结 30 2320
北恋
北恋 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:20

    How about this simple solution:

    const sortCompareByCityPrice = (a, b) => {
        let comparison = 0
        // sort by first criteria
        if (a.city > b.city) {
            comparison = 1
        }
        else if (a.city < b.city) {
            comparison = -1
        }
        // If still 0 then sort by second criteria descending
        if (comparison === 0) {
            if (parseInt(a.price) > parseInt(b.price)) {
                comparison = -1
            }
            else if (parseInt(a.price) < parseInt(b.price)) {
                comparison = 1
            }
        }
        return comparison 
    }
    

    Based on this question javascript sort array by multiple (number) fields

提交回复
热议问题