How to sort an array of objects by multiple fields?

后端 未结 30 2400
北恋
北恋 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条回答
  •  梦毁少年i
    2020-11-21 12:12

    Just another option. Consider to use the following utility function:

    /** Performs comparing of two items by specified properties
     * @param  {Array} props for sorting ['name'], ['value', 'city'], ['-date']
     * to set descending order on object property just add '-' at the begining of property
     */
    export const compareBy = (...props) => (a, b) => {
      for (let i = 0; i < props.length; i++) {
        const ascValue = props[i].startsWith('-') ? -1 : 1;
        const prop = props[i].startsWith('-') ? props[i].substr(1) : props[i];
        if (a[prop] !== b[prop]) {
          return a[prop] > b[prop] ? ascValue : -ascValue;
        }
      }
      return 0;
    };
    

    Example of usage (in your case):

    homes.sort(compareBy('city', '-price'));
    

    It should be noted that this function can be even more generalized in order to be able to use nested properties like 'address.city' or 'style.size.width' etc.

提交回复
热议问题