How to Convert Strings to Arrays in JavaScript

Convert Strings to Arrays in JavaScript

There are several ways to convert strings to arrays, including using the split() method, the Array.from() method, and the spread operator (...). In this article, we will learn about each method and understand the situations in which each method is best used.

One common reason for wanting to convert a string to an array is to make it easier to work with the individual characters in the string. For example, you might want to loop over the characters in a string and perform some operation on each of them. By converting the string to an array, you can use array methods like forEach() to easily iterate over the characters in the string.


split()

The split() method is a string method in JavaScript that allows you to split a string into an array of substrings based on a specified separator. It then returns the new array of substrings.

Here’s an example:

const string = 'hello';
const array = string.split('');
// array is now ['h', 'e', 'l', 'l', 'o']

One important thing to note is that the separator you pass to the split() method can be any string, not just an empty string. For example, you could use a space (' ') as the separator to split a string on spaces and create an array of words:

const string = 'hello world';
const array = string.split(' ');
// array is now ['hello', 'world']

Let’s say you are building a simple to-do list application and want to allow users to enter their to-do items as a comma-separated list. For example, they might enter 'write essay, study for math test, call mom' as their to-do list.

To store the to-do items in your application, you must split this string into an array of individual items. Here’s how you might use split() in this situation:

const toDoListString = 'write essay, study for math test, call mom';
const toDoListItems = toDoListString.split(',');
// toDoListItems is now ['write essay', 'study for math test', 'call mom']

Now that we have our to-do list items in an array, we can easily loop over them, display them on the screen, store them in a database, or do whatever else we need to do with them in our application. Without the split() method, we would have to write a lot more code to manually parse the to-do list string and extract the individual items.


Array.from()

The Array.from() method is a static method in the Array class that creates a new, shallow-copied Array instance from an array-like or iterable object. It has the following syntax:

Array.from(arrayLike, mapFn, thisArg)
  • The arrayLike argument is the array-like or iterable object that you want to convert to an array. This can be any object that has a length property and indexed elements, such as a string or an array-like object (such as an arguments object or a NodeList).
  • The mapFn argument is an optional callback function that will be applied to each element in the resulting array. This can be used to perform some operation on each element in the array, such as mapping the elements to new values.
  • The thisArg argument is an optional value that will be used as the this value inside the mapFn callback function.

Here’s an example of how you might use the Array.from() method to convert a string to an array:

const string = 'hello';
const array = Array.from(string);
// array is now ['h', 'e', 'l', 'l', 'o']

One advantage of using Array.from() over the split() method is that Array.from() can accept any array-like object, not just strings. For example, you could use Array.from() to convert an arguments object to an array:

function myFunction() {
  const args = Array.from(arguments);
  // args is now an array containing the arguments passed to myFunction
}

In this example, we have a function called myFunction that takes any number of arguments. Inside the function, we call Array.from(), passing in the arguments object as the arrayLike argument.

Since the arguments object is array-like (it has a length property and indexed elements), Array.from() is able to create a new array from the elements in arguments. This allows us to work with the arguments passed to myFunction as an array, instead of having to use the arguments object directly.


… (Spread operator)

The spread operator (...) is a syntax in JavaScript that allows you to expand an iterable object (such as an array) into a list of elements. It has the following syntax:

...iterable

The iterable argument is the iterable object (such as an array) that you want to expand. The spread operator will take the elements in the iterable object and expand them into a list of elements.

Here’s an example:

const string = 'hello';
const array = [...string];
// array is now ['h', 'e', 'l', 'l', 'o']

In this example, we have a string called string with the value 'hello'. We want to convert this string to an array of individual characters. To do this, we use the spread operator (...) to expand string into a list of elements. Since string is an iterable object (it is a string, and strings are iterable in JavaScript), the spread operator is able to expand it into a list of individual characters.

Let’s say you are building a simple shopping cart application and want to allow users to add multiple items to their cart at once. You could use the spread operator to combine multiple arrays of items into a single array.

For example:

const fruits = ['apple', 'banana'];
const vegetables = ['carrot', 'potato'];
const cartItems = [...fruits, ...vegetables];
// cartItems is now ['apple', 'banana', 'carrot', 'potato']

In this example, we have two arrays: fruits and vegetables. We want to combine these arrays into a single array of cart items, so we can easily store and display the items in the user’s shopping cart. To do this, we use the spread operator (...) to expand each array into a list of elements, and then we combine the resulting lists of elements into a single array using the array literal syntax ([]). The resulting array is ['apple', 'banana', 'carrot', 'potato'], which contains all the elements from both fruits and vegetables.

Now that we have our cart items in a single array, we can now easily loop over the cartItems array and display the items on the screen. We could also use array methods like forEach(), map(), and filter() to manipulate the items in the array and perform various operations on them.

For example, we could use the filter() method to create a new array of only the fruits in the cart:

const fruitsInCart = cartItems.filter(item => item.includes('fruit'));
// fruitsInCart is now ['apple', 'banana']

Is Object.assign used for this purpose?

I’ve seen some tutorial sites say that Object.assign can be used for converting strings into arrays, but that is not the case. And here’s why not:

const array1 = ['a', 'b', 'c'];
const array2 = [1, 2, 3];

const combinedArray = Object.assign([], array1, array2);
// combinedArray is now ['a', 'b', 'c', 1, 2, 3]

In this example, we have two arrays: array1 and array2. We want to create a new array that includes all these arrays’ elements. To do this, we call Object.assign(), passing in an empty array as the first argument and array1 and array2 as the second and third arguments, respectively. The Object.assign() method then copies all the elements from array1 and array2 into the empty array, creating a new combined array.

However, this is not the same thing as converting a string to an array. If you want to convert a string to an array, you should use one of the methods I mentioned earlier.

Previous Post
Require vs. Import in JavaScript

Require vs. Import in JavaScript

Next Post
Open URL in a New Tab with JavaScript

How to Open URL in a New Tab with JavaScript

Related Posts