0

I can't seem to understand why index is returning undefined. The goal is to place a number in a ordered array, in the correct position. I start by findind the position, but it's returning undefined.

var arr = [3,7,9,12,16,20,31,43,50,55];
var value;
var i=0;
var index;

value = Number(prompt("Enter a value [3,7,9,12,16,20,31,43,50,55]"));
document.write( arr+"<br>");

while(value > arr[i]){

    if (value < arr[i])
    {
        index=i;
    }
    i++;
}

document.write(index+"<br>");

for (i=arr.length-1 ; i>=index; i--){
     arr[i+1] = arr[i];
}

arr[index]=value;
document.write(arr+"<br>");

1 Answer 1

2

For example, if you select 9, the loop goes up to 7 and this is the last value where the while condition is true. The nested check is never reached.

For getting a result, you could take the loop and increment only the index an take the check outside and if the value is smaller or equal, take the index.

var arr = [3, 7, 9, 12, 16, 20, 31, 43, 50, 55];
var value;
var i = 0;
var index;

value = Number(prompt("Enter a value [3,7,9,12,16,20,31,43,50,55]"));
console.log(...arr);

while (value > arr[i]) i++;

if (value <= arr[i]) index = i;

console.log(index);

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, finally i removed the if condition inside the while, leaving index = i;

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.