loading...

re: Keeping Your Code Simple VIEW POST

FULL DISCUSSION
 

Sometimes, there's an even simpler solution:

const strs = ['hello', 'goodbye', 'farewell', 'aloha'];

strs.sort((str1, str2) => str2.length - str2.length);

const longestString = strs[0];
 

I don't think this is a simpler solution, albeit from a logical point of view: it may be understood only considering the outcome of the sorting process, then getting the first item as the one with the minor size...

 

i thought the same... and if you have strings with numbers, then add a return (a-b) or something...

 

Seems that sort has worse performance compared to reduce. Reduce is O(n) while sort is O(n long)

Yes, the performance is worse. But unless you need the solution to scale to arrays with more than a few thousand words, this will hardly be an issue.

True. Just wrote that because it wasn't mentioned anywhere and someone might care about it.

valid point but I agree with Alex... not sure it would really be a thing in an implementation like this

 

If you turn that into a reusable function, you will be mutating the array parameter, i.e. sorting it in-place. You would have to clone the array before sorting it to prevent side effects from passing an array into the function.

Also, you made a mistake. You compare str2.length to str2.length (both are str2).

Use this instead

function longest(xs) {
  // Shallow clone
  xs = [...xs];
  xs.sort((a, b) => b.length - a.length);

  return xs[0];
}

Or with reusable functions

function compareLength(a, b) {
  return b.length - a.length;
}

function head([first, ...rest]) {
  return first;
}

function longest(xs) {
  xs = shallowClone(xs);
  xs.sort(compareLength);

  return head(xs);
}

function shallowClone(xs) {
  return [...xs];
}
 
code of conduct - report abuse