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(" ") ➞ ""
CodePudding user response:
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(" ")) // ""
CodePudding user response:
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)
CodePudding user response:
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"))
CodePudding user response:
let sentence1 = "is2 Thi1s T4est 3a t10at";
let sentence2 = "4of Fo1r pe6ople g3ood th5e the2";
let sentence3 = " ";
function Order(s){
let ordered=[];
let nums = s.match(/\d /g); // get numbers from sentence
if(nums){ // if numbers exist
let numArr=nums.map(Number); // convert string to number
let sortedNum= [...numArr].sort((a,b)=> a-b); // sort numbers
let words= s.replace(/\d /g,'').split(' ') // get words without numbers
sortedNum.map(i=> ordered.push(words[numArr.indexOf(i)])) // get words with order
}
return ordered.join(' ');
}
console.log(Order(sentence1));
console.log(Order(sentence2));
console.log(Order(sentence3));
