Tuesday 22 November 2022

Javascript shift right by 2 and left by 2

 https://stackoverflow.com/questions/16097271/shift-array-to-right-in-javascript



Using .concat() you're building a new Array, and replacing the old one. The problem with that is that if you have other references to the Array, they won't be updated, so they'll still hold the unshifted version.

To do a right shift, and actually mutate the existing Array, you can do this:

arr1.unshift.apply(arr1, arr1.splice(3,2));

The unshift() method is variadic, and .apply lets you pass multiple arguments stored in an Array-like collection.

So the .splice() mutates the Array by removing the last two, and returning them, and .unshift() mutates the Array by adding the ones returned by .splice() to the beginning.


The left shift would be rewritten similar to the right shift, since .push() is also variadic:

arr1.push.apply(arr1, arr1.splice(0,2));

No comments:

Post a Comment