JS | Array advanced methods:
.map()
,.reduce()
. JS | Reference VS value / Shadow copy VS deep copy
The .map()
and .reduce()
methods are methods of the Array object that do not mutate the original array.
- The
.map()
method:- Receives a function as an argument.
- Returns a manipulated array of the same length as the original.
- Transfers to each position of the resulting array the return of the argument function.
const values = [2, 4, 6] const doubledValues = [2, 4, 6]. const doubledValues = values.map(elm => elm * 2) // [4, 8, 12].
- The
.reduce()
method:- Receives as an argument a function with two default parameters: accumulator and iterated value.
- Can receive a second argument as the initial value for the accumulator.
- Takes as the value of the accumulator for the second and successive iterations the value returned from the previous iteration.
const values = [2, 4, 6] const sum = values. const sum = values.reduce((acc, elm) => acc + elm) // 12
The falsie values (null, undefined, false, NaN, 0, ''
) are rejected by default in conditional structures. Every other value (truthy) is accepted by default.
It is possible to make a deep copy of both an object/array and all objects/arrays inside it through the JSON.parse(JSON.stringify(myArray))
technique (more info: parse, stringify).