Problem
- 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.
- Numbers can be from 1 to 9.
- So 1 will be the first word (not 0).
Solution 01
function orderWords(str) {
return str.split(' ').sort((a, b) => a.match(/\d+/g) - b.match(/\d+/g)).join(' ');
}
orderWords('T4est is2 Thi1s 3a'); // Thi1s is2 3a T4est
orderWords('is2 Thi1s T4est 3a'); // Thi1s is2 3a T4est
orderWords('3a is2 T4est Thi1s'); // Thi1s is2 3a T4est
Solution 02
function orderWords(str) {
return str.split(' ').sort((a, b) => a.replace(/[^\d]/g, '') - b.replace(/[^\d]/g, '')).join(' ');
}
orderWords('T4est is2 Thi1s 3a'); // Thi1s is2 3a T4est
orderWords('is2 Thi1s T4est 3a'); // Thi1s is2 3a T4est
orderWords('3a is2 T4est Thi1s'); // Thi1s is2 3a T4est
Solution 03
function orderWords(str) {
return str.split(' ').sort((a, b) => a[a.search(/\d+/g)] = b[b.search(/\d+/g)]).join(' ');
}
orderWords('T4est is2 Thi1s 3a'); // Thi1s is2 3a T4est
orderWords('is2 Thi1s T4est 3a'); // Thi1s is2 3a T4est
orderWords('3a is2 T4est Thi1s'); // Thi1s is2 3a T4est
Solution 04
function orderWords(str) {
let arr = str.split(' ');
let result = [];
for (let i = 0; i <= arr.length; i++) {
for (let j = 0; j < arr.length; j++) {
if (arr[j].indexOf(i) >= 0) {
result.push(arr[j]);
}
}
}
return result.join(' ');
}
orderWords('T4est is2 Thi1s 3a'); // Thi1s is2 3a T4est
orderWords('is2 Thi1s T4est 3a'); // Thi1s is2 3a T4est
orderWords('3a is2 T4est Thi1s'); // Thi1s is2 3a T4est
Solution 05
function orderWords(str) {
let words = str.split(' ');
let result = [];
for (let i = 1; i < words.length + 1; i++) {
result.push(words.find(word => word.includes(i)));
}
return result.join(' ');
}
orderWords('T4est is2 Thi1s 3a'); // Thi1s is2 3a T4est
orderWords('is2 Thi1s T4est 3a'); // Thi1s is2 3a T4est
orderWords('3a is2 T4est Thi1s'); // Thi1s is2 3a T4est