sourlemonaid - 4 months ago 12

Javascript Question

I have a string of numbers. each number has a letter randomly placed inside of the number. I need to sort those numbers based on the letter inside of each number alphabetically. However if there are duplicates, I have to keep the order from the original string. for example: "c21 32b 43a 2c3" must be sorted to "43a 32b c21 2c3" then i need to strip the letters out.

here is what i have so far:

`function cats(s) {`

let arr = s.split(' ').sort(function (a,b) {

return a.match(/[a-z]/i)[0].localeCompare(b.match(/[a-z]/i)[0]);

});

console.log(arr)

for (i = 0; i < arr.length; i++) {

arr[i] = arr[i].replace(/\D/g,'');

}

console.log(arr)

}

cats('y381 6a684 9c94 5x346 c9541 31w1 440x16 x620 1b33 y4773 c3019');

I can't seem to get the duplicate letters to sort correctly. this is important because later on i need to perform math on these numbers and the order is important to get the correct solution.

Answer

You can keep an array of the split strings as a reference and use the index to sort by when the letters match

```
let refArr = s.split(' ');
let arr = refArr.slice().sort(function (a,b) {
let aLetter = a.match(/[a-z]/i)[0], bLetter=b.match(/[a-z]/i)[0];
if(aLetter === bLetter){
return refArr.indexOf(a) - refArr.indexOf(b);
}else{
return aLetter.localeCompare(bLetter);
}
});
```