[JS] Use the array method sort to sort, and complete the array sorting according to the date size

This article mainly describes the use of the array sorting method sort() to sort by date. Go to sort() usage method

1 Encapsulation for comparison method compare

Two parameters:

Parameter 1 is: 排序用的字段;
Parameter 2 is: whether to sort in ascending order true 为升序,false 为降序

Above code:

const compare = (attr, rev) => {
    
    
  rev = (rev || typeof rev === 'undefined') ? 1 : -1;
  return (a, b) => {
    
    
    a = a[attr];
    b = b[attr];
    if (a < b) {
    
     return rev * -1; }
    if (a > b) {
    
     return rev * 1; }
    return 0;
  };
};

2 Example use

Prepare an array to be sorted, where the time attribute is date as the field to be compared:

const arr = [
  {
    
     id: 1, time: "2022/09/09" },
  {
    
     id: 2, time: "2022/09/10" },
  {
    
     id: 3, time: "2022/09/11" },
  {
    
     id: 4, time: "2022/10/01" },
  {
    
     id: 5, time: "2022/10/02" },
  {
    
     id: 6, time: "2022/10/03" },
  {
    
     id: 7, time: "2022/01/01" },
  {
    
     id: 8, time: "2022/02/01" },
  {
    
     id: 9, time: "2022/03/01" },
];

Use the encapsulated compare method in the sort method:

const DESC = arr.sort(compare("time", false)); // 降序

console.log("DESC", DESC);

insert image description here

const ASC = arr.sort(compare("time", true)); // 升序

console.log("ASC", ASC);

insert image description here

Guess you like

Origin blog.csdn.net/qq_53931766/article/details/126782508