Riya
Riya

Reputation: 425

JavaScript: sorting string according to numbers it contains

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");

Upvotes: 2

Views: 78

Answers (3)

slider
slider

Reputation: 12990

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);

Upvotes: 0

Ele
Ele

Reputation: 33726

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);

Upvotes: 0

Mark
Mark

Reputation: 92440

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)

Upvotes: 3

Related Questions