How to sort an array of objects by multiple fields?

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

    I was looking for something similar and ended up with this:

    First we have one or more sorting functions, always returning either 0, 1 or -1:

    const sortByTitle = (a, b): number => 
      a.title === b.title ? 0 : a.title > b.title ? 1 : -1;
    

    You can create more functions for each other property you want to sort on.

    Then I have a function that combines these sorting functions into one:

    const createSorter = (...sorters) => (a, b) =>
      sorters.reduce(
        (d, fn) => (d === 0 ? fn(a, b) : d),
        0
      );
    

    This can be used to combine the above sorting functions in a readable way:

    const sorter = createSorter(sortByTitle, sortByYear)
    
    items.sort(sorter)
    

    When a sorting function returns 0 the next sorting function will be called for further sorting.

提交回复
热议问题