0

I have the following set of array of strings, where I need to rearrange the final output based upon the dates, which need to be sorted earliest to oldest

[
  "2015-08, xyz, 4",
  "2016-03, abc, 5",
  "2015-12, ter, 76",
  "2015-12, rep, 14"
]

The final output needs to looks like

[
  "2016-03, abc, 5",
  "2015-12, ter, 76, rep, 14",
  "2015-08, xyz, 4"
]

How can i go about doing this?

RRP
  • 2,563
  • 6
  • 29
  • 52
  • 1
    and what exactly is your question here? Or are you just hoping someone will do all the hard work for you? – Liam Oct 04 '17 at 07:40
  • @Liam absolutely not, just looking for some guidance on approaching the problem (pseudocode format) – RRP Oct 04 '17 at 07:44
  • Just use default .sort() and then reverse the array. As long as the string start with the year followed by the daya s two numbers, .sort().reverse() works. It only gets tricky when dates aren't written in a format that allows to sort by string value instead of actual date. ( eg, euro format of DD/MM/YYYY cannot be sorted by default as strings ) I'll let you figure out the merging of the strings yourself, since it has nothing to do with the sorting. – Shilly Oct 04 '17 at 08:03

1 Answers1

2

Not a complete solution, but it will give you a basis to implement yours.

Sort your data:

The idea is that you define a function (SortByDate in our example) which contains the logic on how to compare two of your array elements and then call the default sort function with parameter the new function you defined.

data = [
  "2015-08, xyz, 4",
  "2016-03, abc, 5",
  "2015-12, ter, 76",
  "2015-12, rep, 14"
];



//This is the logic
function SortByDate(a, b){
  dateA  = a.split(",")[0];     // e.g. a="2015-08, xyz, 4" dateA="2015-08"
  yearA  = dateA.split("-")[0]; // e.g. "2015"
  monthA = dateA.split("-")[1]; // e.g. "08"
  
  dateB  = b.split(",")[0];
  yearB  = dateB.split("-")[0];
  monthB = dateB.split("-")[1];
  
  if (parseInt(yearA) < parseInt(yearB)) return -1;
  if (parseInt(yearA) > parseInt(yearB)) return 1;
  if (parseInt(yearA) == parseInt(yearB)) {
    if (parseInt(monthA) < parseInt(monthB)) return -1;
    if (parseInt(monthA) > parseInt(monthB)) return 1;
    if (parseInt(monthA) == parseInt(monthB)) return 0;
  }

}

data.sort(SortByDate);
console.log(data);

Next steps:

  1. iterate your array again
  2. if you find equal dates
  3. merge these elements

The last part might be tricky, because your array will lose some elements and its size will decrease. You might want to take a look at this: Looping through array and removing items.

tgogos
  • 23,218
  • 20
  • 96
  • 128
  • 1
    Thanks @tgogos i used .sort().reverse(), but the link to merging and removing the element helps – RRP Oct 05 '17 at 18:32