2

I am trying to sort a string which contains a single number from 1-9. For e.g. string is "Ho2w are1 y3ou" then resulting string should be "are1 Ho2w y3ou". For that, I have used for...of loop to iterate over a string and used split to convert it into an array of string and then used sort method but I am not getting an output. Can anyone suggest what's wrong in my program?

code ::

function order(words){
let result = "";
for (let value of words) {
  result += value;
}

let splited = result.split(" ");
  if(words === ""){
    return "";
  }
  return splited.sort((a,b) => a - b);

}

order("Ho2w are1 y3ou");
2
  • result is not defined anywhere? Commented Oct 20, 2018 at 19:19
  • Defined it in program Commented Oct 20, 2018 at 19:21

3 Answers 3

3

You need to somehow find the number in the word that you want to use to sort. One way to do this is with String.match() and a regular expression:

let str =  "Ho2w are1 y3ou"

let sorted = 
str.split(' ')
.sort((a,b) => a.match(/\d+/)[0] -  b.match(/\d+/)[0]) // sort based on first number found
.join(' ')

console.log(sorted)

Sign up to request clarification or add additional context in comments.

7 Comments

Then no need to use for...of loop ?
No need for the for loop. split() makes and array. sort() sorts it, and join() puts it back together as a string.
Why match? the replace function is a better suit for this question.
@Ele, match was the first things that came to mind. Why is replace better?
Thanks @MarkMeyer for your answer.
|
0

You can use the regexp /\s+/ for splitting the array, that way you can match the tab too. And the regexp [^\d+]/g to remove those chars which are not a number and make the comparison with numbers only.

let str = "Ho2w are1 y3ou"

let sorted = str.split(/\s+/)
  .sort((a, b) => a.replace(/[^\d+]/g, '') - b.replace(/[^\d+]/g, '')).join(' ');

console.log(sorted);

Comments

0

You can also extract characters using filter and isNaN and then use parseInt to get their integer value to use for your sorting function.

const str = "are1 Ho2w y3ou";

const ordered = str.split(" ").sort((a, b) => {
  let numA = parseInt([...a].filter(c => !isNaN(c)).join(''));
      numB = parseInt([...b].filter(c => !isNaN(c)).join(''));
  return numA - numB;
}).join(' ');

console.log(ordered);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.