By array chunking, I mean taking an entire array and creating one array containing smaller subarrays of the original array's elements. Not only is ...
For further actions, you may consider blocking this person and/or reporting abuse
Nothing beats a recursive solution when it comes to elegance IMO.
If you're already in the mood for elegance, why not use a single expression arrow function?
because IMO that's not more elegant.
I think guard clauses should live in the
if
statement that has nothing to do with the rest of the code. I think it is easier to read.But I believe there is no absolute "elegance". Programming is just like art, different people perceive a piece differently.
Mm, Jason's version looks more readable to me. It's laid out a little more like you would if you were matching patterns in Haskell or something.
Here are my 2 cents. It is performant and avoids recursion.
It's funny where a practitioner's blindspots can grow. I literally wouldn't have known exactly what array chunking was. I could guess, but the specific named concept just was not part of my vocabulary.
Just goes to show how random and non-linear the software learning curve is.
This is generally how I do it if I need to partition and I don't have a utility library.
Array.splice is a big no-no.
Can you elaborate why is that?
This is because
Array.prototype.splice
does whatever it does in place. Meaning that it mutates the original array. Mutation are usually consider to make code hard to reason about unless it is very explicit (likeobj.setName('jason')
).Going back to the
chunk
example, consider the following code:What would you expect to be logged? I guess you would probably expect:
But since Ryan suggested to use
splice
, it edits ourarr
in place. And the actual log you will see is:A way to fix this is to clone the whole array before doing anything.
Or a more ES6+ method using array spread (preferable):
I hope I explained this properly.
Couldn't have explained it better.
Thank you Basit and Jason for clearing this up! I certainly should have mentioned the dangers of mutating our original dataset.
Nonetheless, having knowledge of how to use .splice as well as it's dangers could show mastery of JS in the context of an interview <3
Or something like:
That's kind of hard to read (mostly because it's all on one loooong line).
Or even shorter 🤣
another simple loop version
Learned something new today. ! ~_~
But I am unable to see the use case for this. Why would I need to do chunking in the first place?
When you need to fetch something from a 3rd party server and that server only accepts 1000 ids.. So you may need chunking for your 5000 id numbers :)