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

Top comments (0)