Home > Enterprise >  How to arrange years in order in js
How to arrange years in order in js

Time:08-04

hello i have this array

{
2015,
2016,
2017,
2018,
2019,
22/23,
21/22,
20/21,
19/20
}

What action do I do so that it displays it in such an orderly manner?

22/23
21/22
20/21
19/20
2019
2018
2017
2016
2015

CodePudding user response:

You can do your own custom sort function. so if your array is like this:

var array = [
"2015",
"2016",
"2017",
"2018",
"2019",
"22/23",
"21/22",
"20/21",
"19/20"
]

you can create a sort with function inside:

array.sort(function(x1, y1) {
  x = x1.slice(-2);
  y = y1.slice(-2);

  if (x > y) {
    return -1;
  }
  if (x < y) {
    return 1;
  }
  return 0;
});

Now if we console log we see:

"22/23"
"21/22"
"20/21"
"19/20"
"2019"
"2018"
"2017"
"2016"
"2015"

Now you have the concept, you can play with it and push it to the next level.

CodePudding user response:

I am not sure about input date format, but let's assume that 19/20 means 1920.

You can implement custom sort callback to compare parsed numbers:

const data = [
  '2015',
  '2016',
  '2017',
  '2018',
  '2019',
  '22/23',
  '21/22',
  '20/21',
  '19/20'
]

const sorted = data.sort((a, b) => {
  const parseValue = input => {
    const parts = input.split('/')
    
    if (parts.length === 2) {
      // Convert `19/20` to 1920
      return parseInt(parts[1]   parts[0], 10)
    }
    return parseInt(input, 10)
  }
  
  const result = parseValue(b) - parseValue(a)
  
  if (result === 0) {
    // If equal, add with `/` first
    return b.includes('/') ? 1 : -1
  }
  
  return result
})

console.log(sorted)

CodePudding user response:

Since your input array is invalid...

  1. You used object notation ({})
  2. The elements with slashes in them are strings and need to be quoted

...here's an example that fixes those errors, and provides you with a sorted array of ascending years.

const arr = [
  2015,
  2016,
  2017,
  2018,
  2019,
  '22/23',
  '21/22',
  '20/21',
  '19/20'
];

// Coerce `a` and `b` to strings and compare
// the last two characters. JavaScript will coerce
// the strings to numbers when it does the comparison.
arr.sort((a, b) => {
  return b.toString().slice(-2) - a.toString().slice(-2);
});

console.log(arr);

  • Related