-1

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.

Souvik Ray
  • 2,899
  • 5
  • 38
  • 70

2 Answers2

1

No need for regex, just sort based on the integer value of the second character in each entry:

arr = ["#0abc", "#2egf", "#0pol kol", "#1loa", "#2ko pol"];

arr.sort((a, b) => parseInt(a[1]) - parseInt(b[1]));
console.log(arr);
Nick
  • 138,499
  • 22
  • 57
  • 95
1

You could match the first coming digits and take this value for sorting.

var
    getValue = string => string.match(/\d+/),
    array = ["#0abc", "#2egf", "#0pol kol", "#1loa", "#2ko pol"];

array.sort((a, b) => getValue(a) - getValue(b));

console.log(array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392