From String to Array to String

mehmehmehlol

Megan Lo

Posted on April 23, 2021

From String to Array to String

About Writers

Hello everyone!
Hello GIF
This is Waverley and Megan! We are both tech enthusiasts and graduated from Flatiron School recently. Both of us enjoy writing blogs to help other programmers learn and we learn from writing as well (win-win!). This will be our first time writing blogs on dev.to and collaborating on a series with each other, and we are so excited to create content for you all! Feedback is appreciated as we continue to navigate this process ๐Ÿ™

When we first decided to collaborate we came up with a lot of topics to write about. However, as we are both currently in our job search and as bootcamp graduates, we wanted to work on something that will help us now and others in the future. Ultimately, we decided to have this series focus on data structures and algorithms, something we both feel is important to know but not exactly the easiest to understand.

Also, check out our Medium blogs for more of our work:


Intro

Today, we are going to talk about converting array to string, and vice versa. This is one of the commonly seen strategies that is used when solving string-and-array-related coding questions.

Before we get started, if you are interested in knowing array methods, here's Everything JavaScript Arrays & Array Methods! by Waverley; and for string methods, here's When to Use these String Methods in JavaScript by Megan.


Table of Contents


From Array to String

Something that we often need to do is convert an array to a string. Thankfully JavaScript has two built-in methods to accomplish this: toString() and join().


toString(): Returns a string representing the array and its elements (non-destructive)

Like its name, the toString() method turns the arrayโ€™s elements it was called on to a string. To be more specific, this method joins the array and returns one string containing each array element separated by commas.

Fun fact: JavaScript calls the toString method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation.

const array1 = [1, 2, 'a', '1a'];
console.log(array1.toString());
// "1,2,a,1a"
Enter fullscreen mode Exit fullscreen mode

join(): Join all the elements from an array to a string (non-destructive)

join() creates and returns a string by concatenating, or joining, all of the elements of the array it was called on. By default the elements are separated by commas, however you can specify what you want to join/separate the elements by. On the other hand, if there is only one element in the array, the single item will be returned as a string without separators, and if there are no elements, an empty string is returned.

As mentioned, including an argument for the separator parameter is optional if you want the elements to be joined with a comma. Passing in an empty string as the argument will result in the elements joined without any characters/separators.

Otherwise, the parameter is what you want to separate each pair of adjacent elements of the array for the returned string. If necessary, the separator is converted to a string.

let joinArray = ['Wind', 'Water', 'Fire'];
joinArray.join();      // 'Wind,Water,Fire' b/c no separator so joined with commas and no spaces
joinArray.join(โ€œ, โ€œ);  // 'Wind, Water, Fire' b/c separator is comma and space
joinArray.join(โ€œ + โ€œ); // 'Wind + Water + Fire' b/c separator is space, plus sign, space
joinArray.join(โ€œโ€);    // 'WindWaterFire' b/c separator is an empty string
Enter fullscreen mode Exit fullscreen mode

Back to the Table of Contents


From String to Array

split()

As mentioned above, we can join string from array. We can also split string to array. Here, we are going to utilize the join() example to see the alternative results from above.

let splitToArray = 'Wind, Water, Fire';
splitToArray.split('') 
/* [
     'W', 'i', 'n', 'd', ',',
     ' ', 'W', 'a', 't', 'e',
     'r', ',', ' ', 'F', 'i',
     'r', 'e'
   ], no separators
*/
splitToArray.split(' ') 
// [ 'Wind,', 'Water,', 'Fire' ], split by the whitespaces
splitToArray.split(',') 
// [ 'Wind', ' Water', ' Fire' ], split by commas
// As you can see there're still whitespaces in front of each element
// To solve this, we can do the following:
splitToArray.split(', ')
// [ 'Wind', 'Water', 'Fire' ], split by commas and one additional whitespace
Enter fullscreen mode Exit fullscreen mode

This method is probably the most common way to split a string to an array and join afterwards.

Most of the time, when we want to apply array methods to a given string, this is a go-to method to do so. For instance, if we want to reverse a string:

let example = 'JavaScript';

function reverse(str) {
  return str.split('').reverse().join('');
}

// In comparison to:
function reverse(str) {
  let reversed = '' // having to create a new string takes space
  for (let char of string) {
    reversed = char + reversed
  }
  return reversed;
}
Enter fullscreen mode Exit fullscreen mode

Unless your interviewer specifies reverse() method is not allowed to be used, using the split() and join() method would help create a more readable, cleaner code. Also, since reverse() is not a string method, this is where we can utilize our array method in this case.

Palindrome is also another common question which you can make use of the split() and join()


Array.from(string)

There are two ways you can use Array.from(). Either you want to modify and create a new shallow-copied array OR drumroll please ๐Ÿฅ๐Ÿฅ๐Ÿฅ converting string to array.

// To modify an array (Not the focus of this section)
Array.from([1, 2, 3, 4, 5], x => x * 2)
// [ 2, 4, 6, 8, 10 ]

// Convert string to array
Array.from('JavaScript')
['J', 'a', 'v', 'a', 'S', 'c', 'i', 'p', 't']
Enter fullscreen mode Exit fullscreen mode

Remember, these are just some suggestive ways of converting string to array.
According to this article, using the same reversed example we have above, the runtime of using String.prototype.split() is way faster than using Array.from().
But you know, at least we know Array.from() is one of the possible ways to convert string to array!


Object.assign([], string)

You probably heard of Object.keys(), Object.entries() which would return a new array. What about Object.assign()?
Similar deal!
According to MDN, the definition of Object.assign()

The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the target object.

Object.assign() takes two arguments: target and source. In our case, our target is an empty array [] and our source is the given string (which is an enumerable/ can be iterated object).

const str = "foo";
Object.assign([], str) // ['f', 'o', 'o']
Enter fullscreen mode Exit fullscreen mode

Yay! It works... on the surface... If you move this to TypeScript...


โœ‹๐ŸปPAUSEโœ‹๐Ÿป
For those who are not familiar with TypeScript, don't worry. Here's a quick breakdown. You don't have to fully understand TypeScript. All you have to know is that TypeScript is a superset of JavaScript. Most of the time, variables are assigned to a primitive data type in advance.

// In JS
const num = 1;

// In TS
const num : number = 1;
Enter fullscreen mode Exit fullscreen mode

Cool thing about using TypeScript is that you would also see the variable type by hovering over the variable.

Screenshot from CodeCademy
(Screenshot Credit: CodeCademy -- Learn TypeScript course)

Capiche? Hopefully you got the gist of it. Back to the topic...


If you move this to TypeScript, the type of this new copied array does not return as an array of string. ๐Ÿ˜ฑ
If we look at other methods we mentioned above:

const str = 'foo';

const split = str.split('');
const from = Array.from(str);
Enter fullscreen mode Exit fullscreen mode

Feel free to copy and paste the code to the playground and hover over split and from.
They both return split: string[] and from: string[]. (string[] means array of strings.)

However, when you hover over const obj = Object.assign([], str). It returns...
Screenshot for Object.assign()

obj : never[] & "foo", a.k.a. it is never an array but a string.

Isn't that interesting? ๐Ÿ˜ฎ (thanks to our resource)


Although we have 3 ways to convert strings to array, including the spread operator (will be explained in the Bonus Section below), it seems like split() is the best way to do so!

Back to the Table of Contents


Bonus

Spread Operator

While the spread operator (...) is not specific to arrays, it is something helpful to know and use!

From MDN, the spread operator:

allows an iterable such as an array expression or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected, or an object expression to be expanded in places where zero or more key-value pairs (for object literals) are expected.

In other words, essentially the spread operator takes each of the elements inside of the passed in object or array and adds it to the array it is being added to.

As a result, it is often used when all elements from an object or array need to be included in another list of some kind; typical use cases include copying arrays or concatenating an array to the end of an existing array. However, specifically for copying an array, the spread operator goes one level deep. Meaning that if you spread an array into another array, the array it was spread into will not be nested.

Furthermore, itโ€™s important to know that you cannot spread objects into an array or an array into an object. This is because objects alone are not iterable. However, when used in an array or with iterating functions (such as map or reduce), they become iterable.

Under the hood, when the merging occurs 2 objects together with the spread operator, it is assumed that another iterating function is used. On the other hand, if you spread a string into an array, it will create an array with each char in the string.

// general example
let elements = [1, 2, 3]
let newElement = 4

let constructorArray = new Array(newElement, ...elements)
// [4, 1, 2, 3]

let literalArray = [new element, ...elements]
// [4, 1, 2, 3]

// copying an array- showing how the spread operator does not nest
let a = [[1], [2], [3]]
let b = [...a]

console.log(a) // [[1], [2], [3]]
console.log(b) // [[1], [2], [3]]

b.shift().shift()

console.log(a) // [[], [2], [3]]
console.log(b) // [[2], [3]]

// cannot spread an object into an array
let obj = {'key1': 'value1'}
let array = [...obj]; // TypeError: obj is not iterable

// spreading a string into an array
let test = [..."hello", ...โ€œworldโ€]
console.log(test) // ["h", "e", "l", "l", "o", "w", "o", "r", "l", "d"]
Enter fullscreen mode Exit fullscreen mode

Before You Go...

Let's conclude what we have discussed!

From Array to String, we have...
  • toString()
  • join()
From String to Array, we have...
  • split()
  • Assign.from()
  • Object.assign([], string)

Last but not least, spread operator (...) can be used to convert array to string, and vice versa.

Hope you enjoy our first collab article and please give us feedback if you have!
Thank You GIF

๐Ÿ™Œ๐Ÿป Since we can't co-publish articles, we have to publish the same article in our own individual platform. Please give some shoutout to Waverley.

Back to the Table of Contents


Resources:

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
mehmehmehlol
Megan Lo

Posted on April 23, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About