Search code examples
javascriptlodash

Sort array of strings composed of numbers


I have following array which contains strings;

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

these strings are composed of number (year and month).

Can you tell me why didn't work following function for sorting? I need sort this array from latest date to oldest. In this case from "2018-12" to "2018-1".

I am using lodash in whole project so I try use it here as well.

var result = _.sortBy(data, function(i) {
  var x = i.split("-").map(Number);
  return [x[0], x[1]];
});

can you tell me why this code doesn't work and how to fix it? Thanks.


Solution

  • 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);