How to Convert an Array to a String in TypeScript?

If you are a TypeScript developer working with arrays, this tutorial will be very helpful. In it, I explained how to convert an array to a string in TypeScript.

Let’s understand why you might need to convert an array to a string. Arrays are versatile data structures that can hold multiple values, but sometimes you need to present this data in a more readable format. For instance:

  • Displaying Data: When you need to show array data in a UI component.
  • Logging: For debugging purposes, converting an array to a string can make logs more readable.
  • Storage: Storing array data in a database or sending it over a network often requires string format.

Convert an Array to a String in TypeScript

TypeScript, being a superset of JavaScript, inherits all the methods available in JavaScript for converting arrays to strings. Here are some of the most commonly used methods:

1. Using toString()

The toString() method converts an array to a string, with each element separated by a comma. This method is straightforward but offers limited customization.

const cities: string[] = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"];
const citiesString: string = cities.toString();
console.log(citiesString); // Output: New York,Los Angeles,Chicago,Houston,Phoenix

You can see the exact output after I executed the above TypeScript code:

Convert an Array to a String in TypeScript

Read Convert Boolean to String in TypeScript

2. Using join()

The join() method is more flexible than toString(), allowing you to specify a custom separator.

const cities: string[] = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"];
const citiesString: string = cities.join(", ");
console.log(citiesString); // Output: New York, Los Angeles, Chicago, Houston, Phoenix

By using join(), you can create a more readable string by specifying a separator that suits your needs.

3. Using Template Literals

Template literals provide a way to embed expressions within a string. This method can be useful when you need to add additional formatting or context.

const cities: string[] = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"];
const citiesString: string = `${cities.join(", ")}`;
console.log(citiesString); // Output: New York, Los Angeles, Chicago, Houston, Phoenix

Check out Convert Date to String Format DD/MM/YYYY in TypeScript

4. Using reduce()

For more complex transformations, you can use the reduce() method. This method is powerful and allows for custom logic during the conversion.

const cities: string[] = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"];
const citiesString: string = cities.reduce((acc, city, index) => {
  return index === 0 ? city : `${acc}, ${city}`;
}, "");
console.log(citiesString); // Output: New York, Los Angeles, Chicago, Houston, Phoenix

Here is the exact output in the screenshot below:

invalid character in identifier

Check out Convert Date to String in TypeScript

Handle Different Data Types

While the above examples focus on arrays of strings, you might encounter arrays containing different data types. Let’s explore how to handle these scenarios.

Arrays of Numbers

Converting arrays of numbers to strings follows the same principles. Here’s an example:

const numbers: number[] = [1, 2, 3, 4, 5];
const numbersString: string = numbers.join(", ");
console.log(numbersString); // Output: 1, 2, 3, 4, 5

Arrays of Objects

For arrays of objects, you need to decide which property or properties to include in the string representation.

interface Person {
  name: string;
  age: number;
}

const people: Person[] = [
  { name: "John Doe", age: 30 },
  { name: "Jane Smith", age: 25 },
  { name: "Emily Johnson", age: 35 }
];

const peopleString: string = people.map(person => person.name).join(", ");
console.log(peopleString); // Output: John Doe, Jane Smith, Emily Johnson

Check out How to Append to a String in TypeScript?

Real-World Example

Let’s consider a real-world scenario where you need to display a list of US cities in a user-friendly format. We’ll use an array of city objects and convert it to a string that can be displayed in a UI component.

interface City {
  name: string;
  state: string;
  population: number;
}

const cities: City[] = [
  { name: "New York", state: "NY", population: 8419000 },
  { name: "Los Angeles", state: "CA", population: 3980000 },
  { name: "Chicago", state: "IL", population: 2716000 },
  { name: "Houston", state: "TX", population: 2328000 },
  { name: "Phoenix", state: "AZ", population: 1690000 }
];

const citiesString: string = cities.map(city => `${city.name}, ${city.state}`).join(" | ");
console.log(citiesString); // Output: New York, NY | Los Angeles, CA | Chicago, IL | Houston, TX | Phoenix, AZ

In this example, we create a string that includes both the city name and state, separated by a comma and a space. The individual city strings are then joined with a vertical bar (|) to create a visually distinct separator.

Best Practices

When converting arrays to strings, consider the following best practices:

  • Readability: Choose separators that enhance readability. Commas, spaces, and vertical bars are common choices.
  • Consistency: Maintain a consistent format throughout your application to ensure a uniform user experience.
  • Performance: For large arrays, be mindful of performance. Methods like reduce() can be more computationally intensive than join().

Conclusion

In this tutorial, I have explained how to convert arrays to strings in TypeScript using various methods such as toString(), join(), template literals, and reduce(), etc. I have also explained how to handle strings, numbers, or objects, etc., to perform these conversions efficiently.

You may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.