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

5

4 Answers 4

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 }

1
  • Сondition check is rock! Commented Jan 10, 2022 at 3:35
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);

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}

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.