Page 122 - JavaScript
P. 122
or using arrow functions:
myArray.reduce((a, b) => Math.min(a, b)); // 1
myArray.reduce((a, b) => Math.max(a, b)); // 4
5.1
To generalize the reduce version we'd have to pass in an initial value to cover the empty list case:
function myMax(array) {
return array.reduce(function(maxSoFar, element) {
return Math.max(maxSoFar, element);
}, -Infinity);
}
myMax([3, 5]); // 5
myMax([]); // -Infinity
Math.max.apply(null, []); // -Infinity
For the details on how to properly use reduce see Reducing values.
Flattening Arrays
2 Dimensional arrays
6
In ES6, we can flatten the array by the spread operator ...:
function flattenES6(arr) {
return [].concat(...arr);
}
var arrL1 = [1, 2, [3, 4]];
console.log(flattenES6(arrL1)); // [1, 2, 3, 4]
5
In ES5, we can acheive that by .apply():
function flatten(arr) {
return [].concat.apply([], arr);
}
var arrL1 = [1, 2, [3, 4]];
console.log(flatten(arrL1)); // [1, 2, 3, 4]
Higher Dimension Arrays
Given a deeply nested array like so
https://riptutorial.com/ 79

