JS: Arrays

Theory: Converting strings into arrays

At job interviews, they often ask questions like this:

You have a line of text. You need to capitalize the first letter of each word in the text. For simplicity, we'll assume that we're working with a text with no punctuation marks.

const text = 'hello hexlet';
capitalizeWords(text); // 'Hello Hexlet'

There are many ways to solve it. The more methods suggested, the better. These include:

  1. A character-by-character loop through the string.
  2. Converting it into an array.
  3. Using regular expressions. We'll look at these in another course.

Let's break down the solution that involves using an array. To do this, we use the split() method, which splits the string into parts.

const capitalizeWords = (sentence) => {
  // set the separator as space
  const separator = ' ';
  // split the string by the specified separator
  const words = sentence.split(separator);
  // ...
};

The next step is to bypass the resulting array of words and convert the first letter of each word to uppercase. Strings in JavaScript have no built-in method for this, so we'll write one ourselves.

const capitalize = (text) =>
  (text.length === 0) ? text : `${text[0].toUpperCase()}${text.slice(1)}`;

const capitalizeWords = (sentence) => {
  const separator = ' ';
  const words = sentence.split(separator);
  // Forming an array of processed words
  const capitalizedWords = [];
  for (const word of words) {
    capitalizedWords.push(capitalize(word));
  }

  // Combining the processed words back into a sentence
  return capitalizedWords.join(separator);
};

The last action is the inverse of the first. You need to connect the words and return the resulting string.

There's something interesting to note here. The conversion to uppercase occurs not in the words array, but rather in a new one. Why This kind of code makes debugging much easier. If the algorithm does not work correctly, you can always check what's in the words array and what's in the capitalizedWords array. If we changed the words array, then we'd lose this information.

Recommended programs

Completed

0 / 22