I am trying to write a function that takes an array and returns a new array with all elements shifted n indices to the left. For example:
rotLeft([1,2,3,4],2)
// should return [3,4,1,2]
I wrote a recursive function that removes the value at index 0 and assigns it to last index using .shift() and .push().
const rotLeft = (array, n) => {
console.log(array, n); // <-- this prints out expected array
if (!n) return array; // <-- but this returns undefined! :(
array.push(array.shift());
rotLeft(array, n - 1);
};
console.log(rotLeft([1, 2, 3, 4, 5, 6, 7], 9));
How come each console.log(array) prints out the expected array but the array is undefined when the function returns?
You are not returning the rotated array (for each recursive call), you need another return for rotLeft(array, n - 1):
const rotLeft = (array, n) => {
// console.log(array, n);
if (!n) return array;
array.push(array.shift());
return rotLeft(array, n - 1); // <-- return the rotated array (recursively)
};
console.log(...rotLeft([1, 2, 3, 4, 5, 6, 7], 2));
Even shorter (with concat and the ternary operator):
const rotLeft = (array, n) => {
return n ? rotLeft(array.concat([array.shift()]), n - 1) : array;
};
console.log(...rotLeft([1, 2, 3, 4, 5, 6, 7], 2));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With