Sort array of objects by single key with date value

后端 未结 19 1593
情话喂你
情话喂你 2020-11-22 10:56

I have an array of objects with several key value pairs, and I need to sort them based on \'updated_at\':

[
    {
        \"updated_at\" : \"2012-01-01T06:25         


        
19条回答
  •  温柔的废话
    2020-11-22 11:41

    I have created a sorting function in Typescript which we can use to search strings, dates and numbers in array of objects. It can also sort on multiple fields.

    export type SortType = 'string' | 'number' | 'date';
    export type SortingOrder = 'asc' | 'desc';
    
    export interface SortOptions {
      sortByKey: string;
      sortType?: SortType;
      sortingOrder?: SortingOrder;
    }
    
    
    class CustomSorting {
        static sortArrayOfObjects(fields: SortOptions[] = [{sortByKey: 'value', sortType: 'string', sortingOrder: 'desc'}]) {
            return (a, b) => fields
              .map((field) => {
                if (!a[field.sortByKey] || !b[field.sortByKey]) {
                  return 0;
                }
    
                const direction = field.sortingOrder === 'asc' ? 1 : -1;
    
                let firstValue;
                let secondValue;
    
                if (field.sortType === 'string') {
                  firstValue = a[field.sortByKey].toUpperCase();
                  secondValue = b[field.sortByKey].toUpperCase();
                } else if (field.sortType === 'number') {
                  firstValue = parseInt(a[field.sortByKey], 10);
                  secondValue = parseInt(b[field.sortByKey], 10);
                } else if (field.sortType === 'date') {
                  firstValue = new Date(a[field.sortByKey]);
                  secondValue = new Date(b[field.sortByKey]);
                }
                return firstValue > secondValue ? direction : firstValue < secondValue ? -(direction) : 0;
    
              })
              .reduce((pos, neg) => pos ? pos : neg, 0);
          }
        }
    }
    

    Usage:

    const sortOptions = [{
          sortByKey: 'anyKey',
          sortType: 'string',
          sortingOrder: 'asc',
        }];
    
    arrayOfObjects.sort(CustomSorting.sortArrayOfObjects(sortOptions));
    

提交回复
热议问题