The next version of ECMAScript was released in 2019. Below you will learn about array flattening and removing whitespace from a string.
What is array flattening
Flattening consists of transforming an array of arrays to a single dimension. The flat
and flatMap
methods will allow you to perform the flattening.
Flat method
The flat
method returns an array where the sub-arrays have been propagated to a specified depth.
This method is immutable, that is, it returns a new array with the changes and does not change the original array.
This method takes one argument:
- The depth of flattening, by default, has a value of 1.
If it is desired to flatten all sub-arrays in a single dimension, it uses the value of Infinity
.
const array = [1,2,[3,4],5,6]const result = array.flat() result//const array2 = [1, 2, [3, 4, [5, 6]]];const result2 = array2.flat() result2//const array3 = [1, 2, [3, 4, [5, 6]]]const result3 = array3.flat(2) result3//const array4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]const result4 = array4.flat(Infinity) result4///
FlatMap method
The flatMap
method is a combination of the map
and flat
methods. It first iterates the array
elements (as if it were map
), and then flattens them to a single depth (as if it were flat
).
This method is immutable, that is, it returns a new array with the changes and does not change the original array.
This method takes the same arguments as the map method.
const strings = ['Never even', 'of Learn'] strings.map(string => string.split(" "))strings.flatMap(string => string.split(" "))const numbers = [1,2, 3, 4] numbers.map(number => [number * 2])numbers.flatMap(number => [number *2])const numbers2 = [1,[2,3], 4, 5] numbers2.flatMap(number => [number *2])
Removing whitespace from a string
There are three methods to remove whitespace from a string:
- The
trim
method removes whitespace at the beginning and end.
- The
trimStart
or trimLeft
method removes leading blanks.
- The
trimEnd
or trimRight
method removes spaces at the end.
const greeting = " hello"const result1 = greeting.trim()const result2 = greeting.trimStart()const result3 = greeting.trimEnd() result1 result2 ' .
Contribution created by Andrés Guano (Platzi Contributor).
Want to see more contributions, questions and answers from the community?