DEV Community is a community of 614,720 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Discussion on: Keeping Your Code Simple

Alex Lohr

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];
Nando

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...

Lars Gyrup Brink Nielsen • Edited

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).

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;
}

return first;
}

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

}

function shallowClone(xs) {
return [...xs];
}
theMightiestT

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

Evaldas

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