🌟 Introduction
When it comes to programming finding solutions often involves approaches, each with its own advantages and disadvantages ...
For further actions, you may consider blocking this person and/or reporting abuse
A few issues and points here:
0,1 - Get the Smallest/Largest Element of an Array:
As Tamimul pointed out, this can be much shorter - although shorter again from his version (there's little point wrapping an inbuilt function in another function - this will just add overhead):
2 - Shuffle an array
Whilst this works, it's inefficient and will show bias in the shuffling. The Fisher-Yates shuffle is a far better way to do this.
3 - Group an array by an object property
This is built in to JS -
Object.groupBy
- and enjoys broad support on most modern browsers.4 - Reverse a string
The version shown will break with strings such as
"Hello world 😊"
. The following version has issues of it's own, but is much better:6 - Check if Two Arrays Contain the Same Values
The provided function doesn't work in some situations:
8 - Conditional Flow Control with Nested Ternaries
Nested ternaries are never a good idea - very poor readability. Also, your code is a really bizarre way of achieving it's goal. Why not just:
Whoah somehow I never clocked that
Math.random() - 0.5
would give biased results when passed as a sorting function, though I guess it's obvious with the benefit of hindsight.Although you very much seem like a nerd, but your approach is much nicer and smarter
Depends how big your arrays are. This will work fine for a 100,000 element array but throw
RangeError: Maximum call stack size exceeded
for a million elements... whereas thereduce
version will work for either.@lionelrowe this is super interesting! I ended up using
console.time()
to check and see the execution time for both of these methods and while theMath.max(...arr)
version ended up performing faster than the.reduce()
method, you're 100% right. For me, it capped out if I put 130,000 elements into my array.So while the
![Image description](https://media2.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fyfk2fp9cps5yf7fvxokg.JPG)
Math.max()
way is more efficient, I'm guessing JavaScript's callstack can handle only so many execution contexts.Here's the code if anyone wants to copy/paste to fiddle with it:
An excerpt from this great blog
Thnx! Very, very helpful!
Thanks! I appreciate that comment.
This is super cool ! I didn’t realise you could do this !
Thanks, this will help me all I need is to practice using them more.
Exactly! Happy Coding!
I prefer this way