"...is not a function." Why am I getting this error?

Hi,

Currently working on the “Where do I belong?” algorithm. This is my code:

function getIndexToIns(arr, num) {

  var pushed = arr.push(num);

  var sorted = pushed.sort(function(a, b) {
    return a - b;
  });

  return sorted;

}

getIndexToIns([40, 10, 60, 55, 7], 30);

I get an error, however, that “pushed.sort is not a function”.

I don’t understand what the issue is, however. The logic (as I see it) is as follows:

  1. “var pushed” moves the value of the “num” argument into the “arr” argument, thus creating a new array called “pushed”. This is so that I can deal with all numbers at once.

  2. “var sorted” takes the new “pushed” arr and sorts it descending order by way of an a - b function. This is where the error comes up.

  3. “return sorted” should now return this sorted array.

What am I missing?

Thank you.

Hi @asherem

arr.push mutates the original array, but it doesn’t return that array nor a new array.

Have a look at the docs, you should be able to see the problem.

1 Like

arr.push(num)[quote=“asherem, post:1, topic:84769”]
“var pushed” moves the value of the “num” argument into the “arr” argument, thus creating a new array called “pushed”.
[/quote]

No … arr.push(num) … puts the num into the arr array … so it now is [40,10,60,55,7,30]
var pushed = arr.push(num) … read right to left arr pushes num to array as above … then pushed is the length of the array … so its 6

its can be little confusing as if you then do sorted = arr.sort(function …etc
sorted would equal [7,10,30,40,55,60]

best advice i can give is step through your code in something like www.pythontutor.com and you can see what happens

1 Like

thanks for that LINK :thumbsup:

Thanks! Got it now. I remember reading the same now.

1 Like