Skip to main content
edited body
Source Link
georg
  • 214.7k
  • 56
  • 321
  • 397

I added a few more dates as proof.

let data = ["2018-1", "2018-5", "2018-11", "2018-2", "2018-10", "2018-12", "2017-5", "2019-12"];

var result = data.sort((a, b) => {
  var n1 = a.split("-");
  var n2 = b.split("-");
  n1 = parseInt(n1[0]) * 100 + parseInt(n1[1]);
  n2 = parseInt(n2[0]) * 100 + parseInt(n2[1]);
  return n1 <- n2;
})

console.log(result);

I added a few more dates as proof.

let data = ["2018-1", "2018-5", "2018-11", "2018-2", "2018-10", "2018-12", "2017-5", "2019-12"];

var result = data.sort((a, b) => {
  var n1 = a.split("-");
  var n2 = b.split("-");
  n1 = parseInt(n1[0]) * 100 + parseInt(n1[1]);
  n2 = parseInt(n2[0]) * 100 + parseInt(n2[1]);
  return n1 < n2;
})

console.log(result);

I added a few more dates as proof.

let data = ["2018-1", "2018-5", "2018-11", "2018-2", "2018-10", "2018-12", "2017-5", "2019-12"];

var result = data.sort((a, b) => {
  var n1 = a.split("-");
  var n2 = b.split("-");
  n1 = parseInt(n1[0]) * 100 + parseInt(n1[1]);
  n2 = parseInt(n2[0]) * 100 + parseInt(n2[1]);
  return n1 - n2;
})

console.log(result);

Source Link
Sebastian Speitel
  • 7.3k
  • 2
  • 20
  • 38

I added a few more dates as proof.

let data = ["2018-1", "2018-5", "2018-11", "2018-2", "2018-10", "2018-12", "2017-5", "2019-12"];

var result = data.sort((a, b) => {
  var n1 = a.split("-");
  var n2 = b.split("-");
  n1 = parseInt(n1[0]) * 100 + parseInt(n1[1]);
  n2 = parseInt(n2[0]) * 100 + parseInt(n2[1]);
  return n1 < n2;
})

console.log(result);