1

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

jabaa
  • 5,844
  • 3
  • 9
  • 30
wos
  • 29
  • 1

4 Answers4

1

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 }
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
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);
Ricky Mo
  • 6,285
  • 1
  • 14
  • 30
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)
Hubert Grzeskowiak
  • 15,137
  • 5
  • 57
  • 74
0

Just use ordinary sort function

const data = ['000-2022', '000-2023', '005-2021', '000-2021', '003-2021', '004-2022', '007-2021']

const result = data.sort((item1, item2)=> {
  const [prior1, year1] = item1.split('-').map(Number);
  const [prior2, year2] = item2.split('-').map(Number);
  const yearRes = year2 - year1;
  
  return (yearRes === 0) 
    ? prior1 - prior2
    : yearRes  
})

console.log(result)
.as-console-wrapper{min-height: 100%!important; top: 0}
A1exandr Belan
  • 4,442
  • 3
  • 26
  • 48