I am attempting to arrange an array of strings based on a character within each string. Here is what I have so far:
function sortStrings(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);
}
sortStrings("24z6 1x23 y369 89a 900b");
The issue arises when I display this array. If I utilize sortedArr.push(arr[i]);
,
then the outcome is:
["24z6", "1x23", "y369", "89a", "900b"]
However, if I use sortedArr.unshift(arr[i]);
, I obtain:
["900b", "89a", "y369", "1x23", "24z6"]
I am puzzled as to why the b
comes before the a
.
All I want is the sorting to be from a-z. When I tried push()
it is correct but reversed (z-a). Using unshift()
gives me the correct order except that the b
and a
are interchanged.