Transformations
Sometimes we want to transform an array into a new array or another kind of value. We can use:
slice
concat
filter
map
flat
reduce
join
When we copy elements from the original array to a new array, we're only copying references. In other words, mutating an element in the copy will mutate it in the original array too. We often call this a "shallow" copy.
Slices
We use slice
to create a copy of part (or all) of an array.
Concat
We use concat
to join multiple arrays in a new array (as an alternative to the spread syntax).
Any parameters that are arrays are flattened into the new array. Any parameters that aren't arrays are added as elements directly.
Spread is usually more concise than
concat
, and therefore more common in code.
Filter
We use filter
to make a new array that contains a subset of the elements of the original.
Map
We use map
to transform each element into a different element (potentially of a different type).
Flat
We use flat
to flatten nested arrays into a single array. There's an optional depth
argument to flatten recursively.
Reduce
We use reduce
to combine each element in the array into a single value (of an arbitrary type).
Join
We use join
to combine each element in the array into a single string, seperated by a separator
string argument.
Each element is first automatically converted to a string with
toString