Jordan Paz
Jordan Paz

Reputation: 391

Function that is intended to return an array is returning undefined. Console.log(array) within function returns the array

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?

Upvotes: 3

Views: 492

Answers (4)

tam.dangc
tam.dangc

Reputation: 2032

Or you can use Array.prototype.slice() to archive this

const arr = [1,2,3,4]

const rotLeft = (arr, n) => arr.slice(n).concat(arr.slice(0,n))

const tmp1 = rotLeft(arr, 2)
const tmp2 = rotLeft(arr, 3)
console.log("tmp1", tmp1)
console.log("tmp2", tmp2)

Upvotes: 0

Jack Bashford
Jack Bashford

Reputation: 44107

You need to return the recursive call.

const rotLeft = (array, n) => {
  if (!n) return array;
  array.push(array.shift());
  return rotLeft(array, n - 1);
};
console.log(rotLeft([1, 2, 3, 4, 5, 6, 7], 9));

Upvotes: 0

Djaouad
Djaouad

Reputation: 22776

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));

Upvotes: 1

Haseeb Afsar
Haseeb Afsar

Reputation: 629

Try this code below. You are not returning the results from function. I just added the return statement

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());
  return rotLeft(array, n - 1);
};

Usage: rotLeft([1,2,3,4],2)

Output enter image description here

Upvotes: 0

Related Questions