admin管理员组

文章数量:1426847

I have a string like this "is2 Thi1s T4est 3a", I would need to sort it, so the array would look like this "Thi1s is2 3a T4est ". Number can appear anywhere in the string. I know how to sort strings alphabetically and how to sort an array of numbers, but how is it done in this case? Is there a method that helps sort it numerically ignoring letters? I have been trying to acplish this task for a while, any help will be appreciated!

I have a string like this "is2 Thi1s T4est 3a", I would need to sort it, so the array would look like this "Thi1s is2 3a T4est ". Number can appear anywhere in the string. I know how to sort strings alphabetically and how to sort an array of numbers, but how is it done in this case? Is there a method that helps sort it numerically ignoring letters? I have been trying to acplish this task for a while, any help will be appreciated!

Share Improve this question edited Aug 10, 2016 at 16:57 Alex asked Aug 10, 2016 at 16:50 AlexAlex 1232 silver badges9 bronze badges 5
  • You'd need to write a function to parse the numbers out of each string, and then make them into their own full number. – Trasiva Commented Aug 10, 2016 at 16:52
  • How is that an array of strings? I see one string. – Mulan Commented Aug 10, 2016 at 16:52
  • Is there a guarantee that each string will only have one number in it? – TAGraves Commented Aug 10, 2016 at 16:52
  • naomik, thanks for pointing out! I corrected that! Does it explain the issues better? – Alex Commented Aug 10, 2016 at 16:57
  • TAGraves, yes, one substring will always have only one number! – Alex Commented Aug 10, 2016 at 17:00
Add a ment  | 

2 Answers 2

Reset to default 9

You could split on spaces and sort based on the numeric value stored in each string:

let words = "is2 Thi1s T4est 3a".split(' ');
words.sort((a, b) => a.replace(/[^\d]+/g, '') - b.replace(/[^\d]+/g, ''));
console.log(words.join(' '));

first define a pare function.

pare = function(x, y) {
  return x.match(/\d+/g)[0] - y.match(/\d+/g)[0];
}

then use it.

var z = "is2 Thi1s T4est 3a";
z.split(" ").sort(pare).join(" ");
//"Thi1s is2 3a T4est"

Or if you prefer one line,

z.split(" ").sort(function(x, y){return x.match(/\d+/g)[0] - y.match(/\d+/g)[0];}).join(" ")

本文标签: javascriptSort a string depending on the number in the substringStack Overflow