Hey, if it works, right?
I would question whether or not a sort would be the best practice here. It seems like overkill. It seems that just finding the largest would be sufficient. It may not seem like much, but if this were a very large array, that could make a huge difference.
Looking back at my original code, I have:
function largestOfFour(arr) {
for (var i = 0 ; i < arr.length ; i++) {
var biggest = 0;
for (var j = 0 ; j < arr[i].length ; j++) {
biggest=Math.max(biggest, arr[i][j]);
}
arr[i] = biggest;
}
return arr;
}
It’s similar to what you’re doing it’s just that in the inner loop I’m searching for the largest instead of sorting. And then I’m writing the answer right back onto the original array. They do the same basic thing, I just still think looking for the largest is going to be O(n) and sorting is going to be O(n log n) at best. On a monstrously large array that could make a difference. It’s worthwhile to think about these things sometimes.
Knowing what I know now, I might have gone for
function largestOfFour(arr) {
return arr.map(function (subArr){
return subArr.reduce(function (prev, cur) {
return (cur > prev) ? cur : prev;
}, 0);
});
}
Using the map function instead of a for loop isn’t necessarily any better or faster (I think) but one could argue that it’s a little cleaner.
Of course, we can use Math.max instead:
function largestOfFour(arr) {
return arr.map(function (subArr){
return Math.max.apply(null, subArr);
});
}
That works too.
I don’t think ES6 is allowed on the fCC challenges, but if it were, we could use the spread operator:
function largestOfFour(arr) {
return arr.map(function (subArr){
return Math.max(...subArr);
});
}
Which is the best? I don’t know. Someone smarter than me could figure out which is faster - though again it won’t make enough of a difference to matter with small arrays like this. And a big question is what is more readable? Sometimes compactness isn’t the best option if you sacrifice readability. I just thought I’d show you some other options.