Here I played with arrays and strings. And with this solution, I got one additional empty space:
function order(words){
let newArr = [];
words.split(" ").map(item =>
newArr[Number(item.replace(/\D/g, ''))] = item);
return words.length === 0 ? '' : newArr.join(' ');
}
The result was:
console.log(order('is2 Thi1s T4est 3a'));
>>" Thi1s is2 3a T4est"
It's more obvious with this example:
console.log([1, undefined, 3].join());
Which returns:
>>"1,,3"
It should return and empty space but it looks like the empty space takes some space😅
So, I used filter() method:
function order(words){
let newArr = [];
words.split(" ").map(item =>
newArr[Number(item.replace(/\D/g, ''))] = item);
return words.length === 0 ? ''
: newArr.filter(e => e !== undefined).join(' ');
}
Top comments (2)
You can use filter like below not to join falsy values.
['a','b','c', null , undefined].filter(a => a).join(' ')
Great! I didn't know that! Thanks