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...
👨🏫 Co-Founder of This is Learning, Organizer of AarhusJS
✍️ Writer, Speaker, FOSS Maintainer 📗 Author
🏆 Microsoft MVP 🌟 GitHub Star
🌊 Nx Champion 🦸 Angular Hero of Education
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).
Sometimes, there's an even simpler solution:
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...
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
tostr2.length
(both arestr2
).Use this instead
Or with reusable functions
You're right.
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