DEV Community

Cover image for undefined to string
Mikayil
Mikayil

Posted on

undefined to string

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"
Enter fullscreen mode Exit fullscreen mode

It's more obvious with this example:

console.log([1, undefined, 3].join());

Which returns: 
>>"1,,3"
Enter fullscreen mode Exit fullscreen mode

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(' ');
}
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
_bkeren profile image
''

You can use filter like below not to join falsy values.

['a','b','c', null , undefined].filter(a => a).join(' ')

Collapse
 
mikayil profile image
Mikayil

Great! I didn't know that! Thanks