How to sort an array of objects by multiple fields?

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

    Wow, there are some complex solutions here. So complex I decided to come up with something simpler but also quite powerful. Here it is;

    function sortByPriority(data, priorities) {
      if (priorities.length == 0) {
        return data;
      }
    
      const nextPriority = priorities[0];
      const remainingPriorities = priorities.slice(1);
    
      const matched = data.filter(item => item.hasOwnProperty(nextPriority));
      const remainingData = data.filter(item => !item.hasOwnProperty(nextPriority));
    
      return sortByPriority(matched, remainingPriorities)
        .sort((a, b) => (a[nextPriority] > b[nextPriority]) ? 1 : -1)
        .concat(sortByPriority(remainingData, remainingPriorities));
    }
    

    And here is an example of how you use it.

    const data = [
      { id: 1,                         mediumPriority: 'bbb', lowestPriority: 'ggg' },
      { id: 2, highestPriority: 'bbb', mediumPriority: 'ccc', lowestPriority: 'ggg' },
      { id: 3,                         mediumPriority: 'aaa', lowestPriority: 'ggg' },
    ];
    
    const priorities = [
      'highestPriority',
      'mediumPriority',
      'lowestPriority'
    ];
    
    
    const sorted = sortByPriority(data, priorities);
    

    This will first sort by the precedence of the attributes, then by the value of the attributes.

提交回复
热议问题