Skip to content

Instantly share code, notes, and snippets.

@FranklinGuan
Last active July 1, 2023 12:37
Show Gist options
  • Save FranklinGuan/48709e21ecede96f474c4afe3c13a296 to your computer and use it in GitHub Desktop.
Save FranklinGuan/48709e21ecede96f474c4afe3c13a296 to your computer and use it in GitHub Desktop.
Your order, please.js 6kyu-Codewars
//link https://www.codewars.com/kata/your-order-please
//Introduction
// 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.
//Examples
// "is2 Thi1s T4est 3a" --> "Thi1s is2 3a T4est"
// "4of Fo1r pe6ople g3ood th5e the2" --> "Fo1r the2 g3ood 4of th5e pe6ople"
// "" --> ""
//The best Practices
function order(words){
return words.split(' ').sort(function(a, b){
return a.match(/\d/) - b.match(/\d/);
}).join(' ');
}
//Others
function order(words){
if (words.length == 0){return words}
let wordsarr = words.split(' ');
let indarr = words.match(/\d/g);
let neword = [];
for (let i=1;i<=indarr.length;i++){
let ind = indarr.indexOf(i.toString())
neword.push(wordsarr[ind])
}
return neword.join(' ')
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment