In my code, I am attempting to sort an array based on two conditions. Specifically, I need to ensure that Pos 10
comes after single digits and follows a specific order after that.
Initially, I tried to prioritize strings containing the word first
, but when sorting alphabetically, it resets A to the top. How can I achieve the desired outcome?
const arr = [
'Pos 10 second',
'Pos 10 A third',
'Pos 10 first',
'Pos 1 second',
'Pos 1 A third',
'Pos 1 first',
'Pos 2 second',
'Pos 2 A third',
'Pos 2 first',
]
const res = arr
.sort((a, b) => {
if (a.includes('first')) {
return -1
} else {
return 1
}
})
.sort((a, b) => a.localeCompare(b, 'en', { numeric: true }))
console.log(res)
/* Expected output
[
'Pos 1 first',
'Pos 1 second',
'Pos 1 A third',
'Pos 2 first',
'Pos 2 second',
'Pos 2 A third',
'Pos 10 first',
'Pos 10 second',
'Pos 10 A third'
] */