this is to return an array of numbers that are the highest value of the arrays inside of the base array. I can get it to work when i use for statements. But I have tried to simplify it, and can't work out why it doesn't work. any help would be appriciated.
function largestOfFour(arr) {
return arr.map((x) => x.reduce((a, c) => c > a ? c : a, 0));
}
let test = [[1, 2, 3][4, 5, 6][7, 8, 9]]
console.log(largestOfFour(test)) // expected output[3, 6, 9] the largest number from each array
CodePudding user response:
You don't need to reduce, you can do it by just Math.max
. like this:
function findMaxNumbers(arr) {
return arr.map((x) => Math.max(...x));
}
let test = [[1, 2, 3],[4, 5, 6],[7, 8, 9]];
console.log(findMaxNumbers(test));
CodePudding user response:
If you have values smaller than zero, you need to remove the start value
x.reduce((a, c) => c > a ? c : a, 0)
^
or use a very small start value, like -Number.MAX_VALUE
.
CodePudding user response:
To get the max of all the maxes, you can reduce the reductions. If you just want the max's, map the reduction.
const maxOfArray = a => a.reduce((a, c) => c > a ? c : a, -Number.MAX_SAFE_INTEGER); // thanks to Nina
const conciseVLAZMax = a => Math.max(...a); // thanks to VLAZ
let a = [
[1, 2, 3],
[6, -1, -2],
[3, 4, 5],
]
let maxs = a.map(maxOfArray);
let maxMax = maxOfArray(maxs);
console.log(maxs);
console.log(maxMax);