Reputation: 1891
I'm working on a freecodecamp challenge, and am wondering why my code doesn't work and how to correct it.
The objective is to "Return an array consisting of the largest number from each provided sub-array."
My attempt was to map the input array using reduce as the map function:
function largestOfFour(arr) {
arr = arr.map(function(innerArray){
innerArray = innerArray.reduce(function(previousValue,currentValue){
return currentValue > previousValue ? currentValue : previousValue;
});
});
return arr;
}
console.log(largestOfFour([[4, 5, 1, 3],[1, 2, 3, 4]]));
Currently the output is: [undefined, undefined]
How should I fix my code?
Upvotes: 2
Views: 199
Reputation: 318212
There's an easier way
function largestOfFour(arr) {
return arr.map(function(innerArray) {
return Math.max.apply(null, innerArray);
});
}
Math.max
can be called with multiple arguments, as in Math.max(3,4,5,6)
would return 6
.
using apply
we can pass an array of arguments to a function, as in .apply(thisValue, [3,4,5,6])
and do the same thing.
Since there's an array of arrays, we can map the outer array, and return the result of Math.max.apply(thisValue, innerArray)
, and since the thisValue
is unimportant here, just passing null
is fine.
Upvotes: 4
Reputation: 13682
Yet another way to solve this
function largestOfFour(arr) {
return arr.map(function(innerArray) {
// sort innerArray ascending
return innerArray.sort(function sort(a, b) {
return a > b;
}).pop(); // << get the last element (the max)
});
}
var result = largestOfFour([
[4, 5, 1, 3],
[1, 2, 3, 4]
]);
console.log(result);
document.write(result);
Upvotes: 1
Reputation: 288220
Inside the map
callback, you should return the result of reduce
:
function largestOfFour(arr) {
return arr.map(function(innerArray){
return innerArray.reduce(function(previousValue,currentValue){
return currentValue > previousValue ? currentValue : previousValue;
});
});
}
Note there are shorter ways of doing that.
Upvotes: 7