forked from HeyDaniyar/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyourOrder-codewar.js
33 lines (29 loc) · 945 Bytes
/
yourOrder-codewar.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//
// Description:
//
// Your task is to sort a given string. Each word in the String will contain a single number. This number is the position the word should have in the result.
//
// Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).
//
// If the input String is empty, return an empty String. The words in the input String will only contain valid consecutive numbers.
//
// For an input: "is2 Thi1s T4est 3a" the function should return "Thi1s is2 3a T4est"
//
//mine
function order(words){
if (words === '') return '';
var wordsArray = words.split(' ');
var len = wordsArray.length, newArray = [];
for(var i = 0; i < len; i++){
var str = wordsArray[i];
var index = parseInt(str.match(/\d+/)[0]);
newArray[index-1] = str;
}
return newArray.join(' ')
}
//others
function order(words){
return words.split(' ').sort(function(a, b){
return a.match(/\d/) - b.match(/\d/);
}).join(' ');
}