DEV Community

Cover image for undefined to string
Mikayil
Mikayil

Posted on

1

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

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

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

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay