0

I'm trying to push values into array by recursive function, but I get the error message "Uncaught TypeError: Array.push() is not a function", although the push() method is a regular array method. Where the problem could be?

let someArr = ['a', 'b', 'c'];
let someNum = 3;

let fillArr = (arr, num) => x = (num != 0) ? fillArr(arr.push(num), num -1) : arr;

console.log(fillArr(someArr, someNum))

// expected output: ['a', 'b', 'c', 3, 2, 1];
// actual output: Uncaught TypeError: arr.push is not a function
2
  • Use concat instead of push Commented Mar 3, 2021 at 11:22
  • 3
    Array.push returns an int, and you're passing that int as argument for arr in your recursive call. Commented Mar 3, 2021 at 11:22

2 Answers 2

3

The comma operator is often overlooked; it could provide a nice escape hatch:

const fillArr =
  (arr, num) =>
    (num === 0
      ? arr
      : fillArr((arr.push(num), arr), num - 1));
//..............^^^^^^^^^^^^^^^^^^^^

fillArr(['a', 'b', 'c'], 3)
//=> ["a", "b", "c", 3, 2, 1]

However you shouldn't work on the original array with Array#push as it will mutate it (unless it was your intention!)

const arr = ['a', 'b', 'c'];
fillArr(arr, 3);
arr;
//=> ["a", "b", "c", 3, 2, 1] Oops!

Instead you should work with a new array:

const arr = ['a', 'b', 'c'];
const fillArr =
  (arr, num, nums = []) =>
    (num === 0
      ? arr.concat(nums)
      : fillArr(arr, num - 1, (nums.push(num), nums)));

fillArr(arr, 3);
//=> ["a", "b", "c", 3, 2, 1]
arr;
//=> ["a", "b", "c"]
Sign up to request clarification or add additional context in comments.

Comments

1

What Mr.@deceze said is correct. If you still want to do that.. Do something like

let fillArr = (arr, num) => x = (num != 0) ? fillArr(arr, num -1, arr.push(num)) : arr;

fillArr will receive someArr got num pushed and the last argument will be ignored

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.