Hey! I'm YCMJason, a Software Engineer in London 👨💻. Love diving into tech puzzles and sharing them! 🧩
All views expressed here are my own opinions, so please take them with a pinch of salt! 🧂
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 (like obj.setName('jason')).
Going back to the chunk example, consider the following code:
But since Ryan suggested to use splice, it edits our arr in place. And the actual log you will see is:
[[1,2,3], [4,5,6], [7,8,9]] // chunks
[] // arr
A way to fix this is to clone the whole array before doing anything.
functionchunk(array,size){// clone the array to avoid touching the original one.array=array.slice(0)//declaring variable 'chunked' as an empty arrayletchunked=[]//looping through the array until it has been entirely "manipulated" or split into our subarrayswhile(array.length>0){//taking the spliced segments completely out of our original array//pushing these subarrays into our new "chunked" arraychunked.push(array.splice(0,size))}//returning the new array of subarraysreturnchunked}
Or a more ES6+ method using array spread (preferable):
functionchunk([...array],size){//declaring variable 'chunked' as an empty arrayletchunked=[]//looping through the array until it has been entirely "manipulated" or split into our subarrayswhile(array.length>0){//taking the spliced segments completely out of our original array//pushing these subarrays into our new "chunked" arraychunked.push(array.splice(0,size))}//returning the new array of subarraysreturnchunked}
Full stack web developer with a passion for consistency, learning from my mistakes and using my gifts to make a significant difference. Experience in Ruby on Rails, Javascript, React
Education
Psychology & Digital Media -- Claremont McKenna College
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