Here is a straightforward approach to the task, although it may not be the most efficient method as the regular expressions are applied frequently during the sorting process:
const numbers = ['x123', 'y123', 'z123', 'a123', 'b123', 'a123' , 'z123'];
console.log(numbers.sort((a,b)=>a.replace(/^z/,"0").localeCompare(b.replace(/^z/,'0'))));
This code snippet arranges elements starting with 'z' at the beginning of the array.
Recent Update:
I revisited this solution after receiving an upvote and decided to enhance the script for better performance, especially when dealing with large arrays. Inspired by @Barmar's suggestion to segregate the "z"-initiated items from the rest, I implemented a case-insensitive sorting algorithm:
const elements=['x123', 'Z112', 'y123', 'z123', '0011', 'A123', 'b123', 'a023', 'z023'],
result=elements.reduce((a,c)=>(a[0+(c[0].toLowerCase()!="z")].push(c),a),[[],[]])
.flatMap(ar=>ar.sort((a,b)=>a.toLowerCase().localeCompare(b.toLowerCase())));
console.log(JSON.stringify(elements));
console.log(JSON.stringify(result));
The statement
a[0+(c[0].toLowerCase()!="z")].push(c)
inserts the current element
c
into either
a[0]
or
a[1]
, based on the comparison
c[0].toLowerCase()!="z"
converted into a numerical value by adding
0
. Both arrays are sorted individually and merged into a single output array using
.flatMap()
. The sorting mechanism relies on
localeCompare()
along with
.toLowerCase()
.