I’ve been going back and refactoring the basic algorithms I did recently and was wondering if there was a best practice concerning javascript. I don’t really know how to best explain it other than by example. I initially solved the “Return Largest Numbers in Arrays” with the following:
function(arr) {
var largest = [];
for (var i = 0; i < arr.length; i++) {
largest.push(arr[i].sort(function(a, b) {
return a - b;
})[arr[i].length - 1]);
}
return largest;
}
I went back and rewrote this as:
function largestOfFour(arr) {
return arr.map(function(i) {
i.sort(function(a, b) {
return a - b;
});
return i[i.length - 1];
});
}
They both work. The second one seems more elegant, but maybe harder to follow. Is one better than the other? Is there any guidelines for a best practice?