sourlemonaid sourlemonaid - 2 months ago 8
Javascript Question

Sort an array of strings based on a character in the string

I am trying to sort an array of strings based on a character inside each of those strings. So far, I have this



function doMath(s) {

let arr = s.split(' ');
let letterArr = [];
let sortedArr = [];
let n = 0;
for (var i = 0; i < arr.length; i++) {

n = arr[i].indexOf(arr[i].match(/[a-z]/i));
letterArr.push(arr[i][n]);

}
letterArr.sort();

console.log(letterArr);

for (i = 0; i < arr.length; i++) {
for (var j = 0; j <= arr[i].length; j++) {

if (arr[i].indexOf(letterArr[j]) > -1) {
sortedArr.unshift(arr[i]);
}

}
}
console.log(sortedArr);
}

doMath("24z6 1x23 y369 89a 900b");





The problem is shown when I log this array. If I use
sortedArr.push(arr[i]);
,
then the output is:

["24z6", "1x23", "y369", "89a", "900b"]


However, when I use
sortedArr.unshift(arr[i]);
, I get the output:

["900b", "89a", "y369", "1x23", "24z6"]


I am not sure why the
b
comes before the
a
.

I just want it to be a-z for the sorting. I tried
push()
and it is correct but backwards (z-a). When I try
unshift()
, it's correct except the
b
and
a
are switched.

Answer

function doMath(s) {
   return s.split(' ').sort(function (a,b) {
      return a.match(/[a-z]/i)[0].localeCompare(b.match(/[a-z]/i)[0])})
}

console.log(doMath("24z6 1x23 y369 89a 900b"));