Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

185
Views
sort strings by string elements

Need help for below scenario

000-2022, 000-2023, 005-2021, 000-2021, 003-2021, 004-2022, 007-2021

last 4 digits are year and middle 3 digits are priority number. I need this to be sorted with highest year first and below it should come the corresponding priority number of that years and then it should move on to the next lesser year.

expected result :

000-2023, 000-2022, 004-2022, 000-2021, 003-2021, 005-2021, 007-2021

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

this way

let arr = ['000-2022', '000-2023', '005-2021', '000-2021', '003-2021', '004-2022', '007-2021']

arr.sort( (a,b)=>
  {
  let [aN,aY] = a.split('-').map(Number)
    , [bN,bY] = b.split('-').map(Number)
  return aY - bY || aN - bN  
  })

console.log(  arr )
.as-console-wrapper {max-height: 100%!important;top:0 }

about 4 years ago · Juan Pablo Isaza Report

0

Use the sort() function for sorting. And use the split() function to split the string.

let arr = ["000-2022", "000-2023", "005-2021", "000-2021", "003-2021", "004-2022", "007-2021"]
arr.sort((a,b)=>{
  let [aPriority,aYear] = a.split("-").map(it => Number(it));
  let [bPriority,bYear] = b.split("-").map(it => Number(it));
  return bYear > aYear ? 1 : 
         aYear > bYear ? -1 : 
         (aPriority - bPriority);
  
});
console.log(arr);

about 4 years ago · Juan Pablo Isaza Report

0

I would strongly recommend sanitising the input data first into a structured format. Then the sorting code will be much easier to understand.

Here's an example:

a = ["000-2022", "000-2023", "005-2021", "000-2021", "003-2021", "004-2022", "007-2021"]
structured = a.map((e) => {
  [priority, year] = e.split("-")
  return {priority, year}
})

// `sort()` changes the array in place, so there's no need for a new var
structured.sort((e1, e2) => {
  if (e1.year !== e2.year) {
    // year is different, so sort by that first
    return e1.year < e2.year && 1 || -1
  } else {
    // if year is the same, sort by priority
    return e1.priority < e2.priority && 1 || -1
  }
})
console.log(structured)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!