I have no clue why I am getting “newArray.sort is not a function” error in this simple code. I can’t figure it out :S
My code
function getIndexToIns(arr, num) {
var newArray = arr.push(num);
var result = newArray.sort(function(a, b){
return a - b;
});
return result;
}
getIndexToIns([40, 60], 50);
Link to the challenge:
https://www.freecodecamp.org/challenges/where-do-i-belong
Array.push()
does not return anything, especially not an array. It is a method of the Array
prototype. It loops over the parameters you give it and adds them to the array. It only seems to return the last parameter value as a form of validation that you could use in a conditional or such.
Your variable newArray
therefore does not contain an array, but the value of num.
If you’re curious, you can replicate the behavior of Array.push()
with this:
let arr = [];
let data = ["Text", 1, false, undefined];
for( let entry of data ){
// Use length of arr as index
// Length measures # of items in array, index their entry so will always be one higher.
arr[arr.length] = entry;
}
// or
for( let i = 0; i < data.length; i++ ){
arr[arr.length] = data[i];
}
1 Like
don’t use .push(num) during assignment. This works:
function getIndexToIns(arr, num) {
var newArray = arr;
newArray.push(num);
var result = newArray.sort(function(a, b){
return a - b;
});
return result;
}
getIndexToIns([40, 60], 50);
1 Like
push
returns the new length of the array, so in your example (getIndexToIns([40, 60], 50);
) you are assigning the number 3 to the variable newArray
on the first line of your function. Don’t assign the return value of push, you’re already directly modifying arr
:
arr.push(num);
var result = arr.sort(function(a, b) {
This is exactly the same as arr.push(num)
because in your code, newArr
is arr
, it’s not a new array.
2 Likes
Thanks to everyone! I really appreciate it <3