Here i have tried
let sen = ("is2 Thi1s T4est 3a")
let sen2 = sen.split(" ")
//console.log(sen2)
sen2.sort()
console.log(sen2)
the output should be like this
rearrange("is2 Thi1s T4est 3a") ➞ "This is a Test"
rearrange("4of Fo1r pe6ople g3ood th5e the2") ➞ "For the good of the people"
rearrange(" ") ➞ ""
You can split based on the numeric value by selecting the number present in word by regex and sort on this numeric value.
const rearrange = (sentence) => {
if(sentence.trim() === "") return "";
return sentence
.trim()
.split(" ")
.map(word => [word.match(/\d+/)[0], word])
.sort((a, b) => a[0] - b[0])
.map(([, word]) => word.replace(/\d+/, ''))
.join(" ");
}
console.log(rearrange("is2 Thi1s T4est 3a")) //"This is a Test"
console.log(rearrange("4of Fo1r pe6ople g3ood th5e the2")) //"For the good of the people"
console.log(rearrange(" ")) // ""
You can try something like this
function rearrange(sen){
let sen2 = sen.split(" ");
sen2.sort(function(a, b){
return parseInt(a.replace(/\D/g,'')) - parseInt(b.replace(/\D/g,''));
});
sen2 = sen2.map(a => a.replace(/\d/g,''));
return sen2.join(" ");
}
You may also need some error handling (In case some words dont have numbers)
function getNumber(s) {
var r = /\d+/;
return s.match(r) || 0;
}
function reArrange(s) {
let s2 = s.split(" ")
s2.sort(function(a, b){return getNumber(a) - getNumber(b)});
return s2.join(' ')
}
console.log(reArrange("4of Fo1r pe6ople g3ood th5e the2"))