Algorithm Scripting Help

Can anyone help me find out what’s wrong with my code? I’ve tested it out and it seems to work on every input so I’m confused.

Your code so far


function sortNumber(a, b) {
return a - b;
}

function getIndexToIns(arr, num) {
arr.sort(sortNumber);
console.log(arr);

for(var x in arr){
  if(arr[x] >= num){
    arr.splice(x , 0, num)
    break;
  }
}
if (num > arr[arr.length - 1]){
  arr.splice(arr.length, 0, num);
  x = arr.length - 1
}
else if (arr.length == 0){
  x = 0
  arr.push(num);
}

console.log(arr);
console.log(x);
return x;
}

getIndexToIns([10, 20, 30, 40, 50], 35);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36.

Challenge: Where do I Belong

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/where-do-i-belong

The problem originates in your for loop. When you use a for...in loop, the variable x is a string and not a number.

Thanks! I added a parseInt(x) line before returning x and it worked out just fine.

Because for…in loop is designed to go through the properties of an object. The variable x will be a string type. For array, it is better to use for instead. For your reference.

Came from https://www.w3schools.com/jsref/jsref_forin.asp
JavaScript supports different kinds of loops:
for - loops through a block of code a number of times
for/in - loops through the properties of an object
for/of - loops through the values of an iterable object
while - loops through a block of code while a specified condition is true
do/while - loops through a block of code once, and then repeats the loop while a specified condition is true
Note Do not use the for/in statement to loop through arrays where index order is important. Use the for statement instead.

2 Likes