Converting between strings and arrays

Often you'll be presented with some raw data contained in a big long string, and you might want to separate the useful items out into a more useful form and then do things to them, like display them in a data table. To do this, we can use the split() method. In its simplest form, this takes a single parameter, the character you want to separate the string at, and returns the substrings between the separator as items in an array.

Note: Okay, this is technically a string method, not an array method, but we've put it in with arrays as it goes well here.

  1. Let's play with this, to see how it works. First, create a string in your console:
  2. const data = "Manchester,London,Liverpool,Birmingham,Leeds,Carlisle";
  3. Now let's split it at each comma:
  4. const cities = data.split(",");
    cities;
  5. Finally, try finding the length of your new array, and retrieving some items from it:
  6. cities.length;
    cities[0]; // the first item in the array
    cities[1]; // the second item in the array
    cities[cities.length - 1]; // the last item in the array
  7. You can also go the opposite way using the join() method. Try the following:
  8. const commaSeparated = cities.join(",");
    commaSeparated;
  9. Another way of converting an array to a string is to use the toString() method. toString() is arguably simpler than join() as it doesn't take a parameter, but more limiting. With join() you can specify different separators, whereas toString() always uses a comma. (Try running Step 4 with a different character than a comma).
  10. const dogNames = ["Rocket", "Flash", "Bella", "Slugger"];
    dogNames.toString(); // Rocket,Flash,Bella,Slugger