[SOLVED] Angular, how to sort correctly the date in the string the strings?


I have these two strings:

"2022 | Dec (V2 2022)"
"2022 | Jul (V1 2022)"

And I want to sort them correctly, for now, I am using localeCompare but doesn’t work properly
As I get "2022 | Jul (V1 2022)", the second and it should be the first.
Can sb help me, please?


You’ll have to convert your strings into date objects first and then you can perform sorting.

Now your strings are in a specific format that no date library would recognize (so you’ll have to devise your own strategy to convert the strings into date)

You can take help from string manipulation methods available in javascript, along with map and sort array methods, I’ve create a sample code that works for me

let arr=['2022 | Dec (V2 2022)', '2022 | Jul (V1 2022)'];
let sortedArr = arr.map(x=>{
  let dtString = x.replace(x.substring(x.indexOf('('),x.length),'');
  dtString = dtString.replace('|','-').replace(/ /g,'');
  return {originalTxt: x, date: Date.parse(dtString)};
}).sort((a,b)=>{return a.date - b.date;}).map(x=>x.originalTxt);


So basically what I did was, stripped off the text in parenthesis and replaced pipe character (|) with dash (-) character and stripped off empty spaces, so that the string looks like ‘2022-Dec, 2022-Jul’, and converted this to date (now its convertable) and to keep the original string I created an object with date and originalTxt. Performed sorting with sort js method and showed the original text again. (It was sorted now)

Answered By – Obaid

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *