HELP_Where do I belong

Tell us what’s happening:
I’m getting the error message
TypeError: newArr.sort is not a function

Your code so far


Insert the value (second argument) into the array.
Sort the array with the second argument in it.
Find the index of the second argument.

*/



function getIndexToIns(arr, num) {
  var newArr = [];
  newArr = arr.push(num);
  newArr.sort(function(a, b){
    return a - b;
  });
  var index;
  index = newArr.findIndex(num);
  return index;
}



getIndexToIns([40, 60], 50);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36.

Link to the challenge:
https://www.freecodecamp.org/challenges/where-do-i-belong

The value return by the push() method is the length of the new array (MDN reference). As such, the following in in your code is actually not creating a new array:

newArr = arr.push(num);

What it’s actually doing is this:

// ...
console.log(arr, num); // [40, 60], 50
newArr = arr.push(num);
console.log(arr); // [40, 60, 50]
console.log(newArr); // 3
// ...

And that is the reason why you get TypeError: newArr.sort is not a functionnewArr in your code is a number and not an array.

I hope that helps. :slight_smile:

/*Pseudocode:

Insert the value (second argument) into the array.
Sort the array with the second argument in it.
Find the index of the second argument.

*/

function getIndexToIns(arr, num) {
  arr.push(num);
  arr.sort(function(a, b){
    return a - b;
  });
  function findNumber(num) { /*findNumber because the documentation specified a testing function to be specified. Could I use findIndex(num) directly? */
}
  var index;
  index = arr.findIndex(findNumber);
  return index;
}

getIndexToIns([40, 60], 50);

The below does not satisfy any criteria. Returns -1. Why?

function getIndexToIns(arr, num) {
  arr.push(num);
  arr.sort(function(a, b){
    return a - b;
  });
  function findNumber(num) { 
}
  var index;
  index = arr.findIndex(findNumber);
  return index;
}