Transforming an array
JavaScript also has support to methods that can modify the elements of the array or change its order. We have covered two transformative methods so far: reverse
and sort
. Let's learn about other useful methods that can transform the array.
Mapping values of an array
The map
method is one of the most used methods in daily coding tasks when using JavaScript or TypeScript. Let's see it in action:
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const squaredNumbers = numbers.map(value => value * value);
console.log('Squared numbers:', squaredNumbers);
Suppose we would like to find the square of each number in an array. We can use the map method to transform each value within the array and return an array with the results. For our example, the output will be: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
.
We could rewrite the preceding code using a for
loop to achieve the same result:
const squaredNumbersLoop = [];
for (let i = 0; i < numbers.length...