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

57
June 16, 2019, at 12:20 PM

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?

Answer 1

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

Answer 2

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

Answer 3

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

READ ALSO
Selenium Actions moveToElement on Google Chrome 75.0.3770.80 on ubuntu doesnot work

Selenium Actions moveToElement on Google Chrome 75.0.3770.80 on ubuntu doesnot work

Selected an element and wanted --> physically move the mouse cursor over it

29
React hook setState arguments

React hook setState arguments

I would like to know the difference between the following two versions of codeBoth versions do the same

52
Angular material data table not displaying service data

Angular material data table not displaying service data

I'm trying to display some data in angular material data-table,my service class method has data but its not displaying in data-table, please help me ,am unable to find mistake in data-table from last 3 hours

26