wos
wos

Reputation: 29

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

Upvotes: 1

Views: 68

Answers (4)

Hugo G
Hugo G

Reputation: 16496

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)

Upvotes: 0

Mister Jojo
Mister Jojo

Reputation: 22295

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 }

Upvotes: 1

A1exandr Belan
A1exandr Belan

Reputation: 4780

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}

Upvotes: 0

Ricky Mo
Ricky Mo

Reputation: 7628

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);

Upvotes: 0

Related Questions