【TypeScript】Sort by comparing multiple keys in an associative array.

Compare multiple keys in an associative array using JavaScript sort().

The official is here.

The sort() function can be passed a function that defines the sort order.
The sort() function accesses a reference to the original array.

目次

Definition of associative array

Defines an associative array.

SortType defines the creation date and time (createdAt) and the update date and time (updatedAt).
The updatedAt also allows the field to be absent.

export type SortType = {
  createdAt: Date;
  updatedAt?: Date;
};

const sortData: SortType[] = [
  {
    createdAt: new Date('2020-01-01'),
    updatedAt: new Date('2020-02-01'),
  },
  {
    createdAt: new Date('2020-01-01'),
    updatedAt: new Date('2020-02-01'),
  },
  {
    createdAt: new Date('2020-01-01'),
  },
];

Sort associative arrays with multiple keys

In the comparison of associative arrays, a comparison is made for each SortType object.
If the updatedAt property exists, updatedAd is used, otherwise createdAt is used for comparison.

The data is stored in the dateA and dateB variables respectively, and if it is smaller, -1 is returned, and if it is larger, 1 is returned for sorting.
In the example below, the data is sorted in descending order.

sortData.sort((a: SortType, b: SortType) => {
  const dateA =
    typeof a.updatedAt === 'undefined' ? a.updatedAt : a.createdAt;
  const dateB =
    typeof b.updatedAt === 'undefined' ? b.updatedAt : b.createdAt;

  return dateA > dateB ? -1 : 1;
});

Summary

The sort() function is very versatile.
The larger the argument, the less readable it becomes, so make it more readable by making it a function.

よかったらシェアしてね!
目次