I have an array which looks like this
arr = ["#0abc", "#2egf", "#0pol kol", "#1loa", "#2ko pol"]
As you can see, each element in the array has #n
associated with it where n
is any number between 0-9
. Now based on the n
, I want to sort by array in ascending order such that the final output looks like this
[ '#0abc', '#0pol kol', '#1loa', '#2egf', '#2ko pol' ]
So this is what I do
rankWordMap = {}
finalArr = []
arr.forEach(function(entry) {
rank = entry.charAt(1)
if(rankWordMap[rank]) {
rankWordMap[rank].push(entry);
}
else {
rankWordMap[rank] = [entry];
}
})
for (var key in rankWordMap) {
if (rankWordMap.hasOwnProperty(key)) {
finalArr.push(...rankWordMap[key])
}
}
console.log(finalArr)
I get the expected output but as you can see, it's pretty inefficient. Besides I could have hundreds of elements sometimes where I would like to quickly sort it rather than doing it this way.
Is there any shorter way to implement this? I am specifically looking for a regex solution but other solutions are fine too.