Refactoring algorithms

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?

I like the second, which is much more readable to me. The variables arr and i could be renamed for clarity, but it’s still not as difficult to follow as the first. If I were to improve it, I’d say you could reverse the sort order (b - a instead) so that you can return i[0] rather than having to call up the length property. Also, your sorting function duplicates what sort does by default, so you could remove that function altogether if you’re sorting from smallest to largest. Using arrow functions, we can cut out quite a bit:

function largestOfFour(arrays) {
    return arrays.map(arrayOfNumbers => arrayOfNumbers.sort((a, b) => b - a)[0])
}
1 Like