8 minutes read

Now that you have learned how to create and iterate with arrays, it is time for you to take a step further. Sometimes you will get data inside arrays that is not the way you need it to be, so you will need to transform it. In this topic, you will learn how to use the map(), join(), and toString() methods to help you in this situation.

We will start with the map() method and discuss the others in sequence. This method is very useful and popular when it comes to transforming data, so let's begin.

Map method

Let's start with something simple and create an array of numbers.

const numbers = [5, 10, 15, 20, 25];

Now let's say you want to multiply all the values inside this array by 3, but you want to keep the original values of the numbers array unchanged. How would you do it?

You could create a new array with the same size as the numbers array and then assign each value individually corresponding to the position of the numbers array. Let's see an example of that:

let numbersByThree = new Array(numbers.length)

numbersByThree [0] = numbers[0] * 3;
numbersByThree [1] = numbers[1] * 3;

However, this would be tedious and inefficient. Imagine that you have to do this same operation 100 times! It would take a lot of your time.

That's where the map() method comes in to save your time. It creates a new array on top of the original array by performing the desired operation on each element. The syntax of this method is the following:

array.map(function(currentValue, index, arr));
  • function: Required. The function that will be executed for each element of the array.
  • currentValue: Required. Concerns each of the matrix elements, so if you want to multiply by 3 the method will perform this operation on each of the values.
  • index: Optional. It's the index of each element, starting at 0.
  • arr: Optional. It's the array itself.

So to perform the multiplication on the numbers array we don't need to explicitly create a new array. The map method will return a new one. To perform the multiplication we will need a function, so let's make one:

function multiplyByThree(element) {
  return element * 3;
}

Now you can pass this function as an argument to the map() method. Each of the elements will be multiplied by 3 and these values will be stored in a new array. Let's see it in the code:

let numbersByThree = numbers.map(multiplyByThree);

console.log(numbersByThree); // [ 15, 30, 45, 60, 75 ]

Much more convenient and simple than the way we used it before, right? You don't have to worry about creating a new array of the same size and then having to change each value individually, the map() method does it for you.

Using anonymous function

You don't need to explicitly create a function to use with the map() method. Instead, you can use an anonymous function inside the method itself, the code will be executed in the same way as before. It is advisable to use anonymous functions to make your code more readable.

let numbersByThree = numbers.map(function (element) {
  return element * 3;
});

It can be even more convenient, take a look at the arrow function syntax:

let numbersByThree = numbers.map((element) => {
  return element * 3;
});

You can also use built-in functions with map(), for example, the sqrt function of the Math object, which returns the square root of a given number. Depending on the number the result can be a float with several decimal places. We will reduce it to only 2 decimal places for better visualization. You can try floor and ceil functions of the same Math object to see different results.

const numbers = [5, 10, 15, 20, 25];

console.log(numbers.map(Math.sqrt)); // [2.23, 3.16, 3.87, 4.47, 5]

You don't need to explicitly pass each element to the sqrt function, JavaScript understands this syntax perfectly and will perform the operation on each element.

Join method

Imagine you have a set of words and you need to form a sentence with these words separated by a common character. You can achieve it with the join() method: it takes a string separator as an argument, a space array.join(" "), or a comma array.join(",") for example. Let's look at an example to make it clearer.

First, you will need an array with some data, let's create one.

const words = ["JavaScript", "is", "truly", "interesting"];

Now one thing that you should keep in mind is that the join() method does not modify the original array, it takes the original array and returns a string. Therefore, if you run the code below, the words array will remain unchanged.

words.join(" ");
console.log(words); // [ 'JavaScript', 'is', 'truly', 'interesting' ]

To see the result of the join you need to store it in another variable, so let's create a so-called phrase and store the result in it.

const phrase = words.join(" ");
console.log(phrase); // JavaScript is truly interesting

The data in the arrays can also be of other types, such as numbers. The join method will convert it to a single string and if you don't want to save it in another variable, you can print it directly on the console.

const numbers = [1, 2, 3, 4, 5];
console.log(numbers.join("-")); // 1-2-3-4-5

The join() method only works for the array data structure. If you try to use it on another data structure such as string, a TypeError exception will be raised.

toString method

This method as its name suggests converts the elements of an array into a string. This method requires no argument. Let's take our array of numbers as an example.

const numbers = [1, 2, 3, 4, 5];
console.log(numbers.toString()); // 1,2,3,4,5

The result will be a comma-separated string. You can see that the result is similar if you use the join() method but in this case we can't specify the separator. Another difference is that you can use this method on other types of objects such as Number, Function, Object, etc.

Conclusion

In this topic, you have learned three methods for working with arrays, each of them with its specific purpose.

  • The map() method is very useful when you want to transform the data of an array while keeping the original intact.
  • The join() method is very useful when you have an array of separate characters and want to join them together by a common separator. Remember that this method returns a string.
  • The toString() method transforms the elements of a given array into a single string. The difference between it and the join() method is that you cannot specify a separator.
102 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo