DEV Community

Hank X
Hank X

Posted on

3 ways to turn String to Array in JavaScript, and the fastest one is...

This probably an very easy question which you might only see it in intern or junior frontend job interview.

Given a String, turn it into an Array which each character as its item.

eg. Given 'Dev.to', out put ['D', 'e', 'v', '.', 't', 'o'].

Easy, right? The first method comes to your mind must be split.

split

function stringSplit(s){
  return s.split('')
}
Enter fullscreen mode Exit fullscreen mode

And with the power of ES6, you might also know that Array.from can also do this job

Array.from

function arrayFrom(s){
  return  Array.from(s)
}
Enter fullscreen mode Exit fullscreen mode

How about Object.values, of course it works

Object.values

function objectValues(s){
return Object.values(s)
}

Really a simple question, right? Let's see which one is the fastest way.

The simplest way to know how long a method take, it's print the time before and after the execute of the method. So here we get

function callWithTimer(func, s){
  let start = Date.now()
  func(s)
  let end = Date.now()
  let name = func.name
  let diff = end - start
  console.table({
    name,
    start,
    end,
    diff
  })
}
Enter fullscreen mode Exit fullscreen mode

Also a simple function to generate a random string

function randomString(len){
return [...Array(len)].map(() => Math.random().toString(36)[2]).join('')
}
Enter fullscreen mode Exit fullscreen mode

Let's see the simple result:

((len)=>{
  const str = randomString(len)
  callWithTimer(arrayFrom, str)
  callWithTimer(stringSplit, str)
  callWithTimer(objectValues, str)
})(10000000)
Enter fullscreen mode Exit fullscreen mode

Image description

So the old trick is the best :D

Tiugo image

Modular, Fast, and Built for Developers

CKEditor 5 gives you full control over your editing experience. A modular architecture means you get high performance, fewer re-renders and a setup that scales with your needs.

Start now

Top comments (0)

Neon image

Next.js applications: Set up a Neon project in seconds

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Get started β†’

πŸ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay