Sort Array using splice and push and Math.min

Tell us what’s happening:
I have an array of numbers and I want to sort them ascending.
but my loop is not going in all arr.length why!
Copy my code and keep track of the console.log, you will understand the problem.

Your code so far
why the for loop is not working for all (arr.length)!?!


function getIndexToIns(arr, num) {
let x = [] ,y;
for(let i=0; i<=arr.length; i++){
   y = Math.min(...arr); console.log(y)
   x.push(y);console.log(x)
   arr.splice(arr.indexOf(y),1);console.log(arr)
}console.log(x)
}

getIndexToIns([40, 60,70,30,50,100,3,66], 50);

Your browser information:

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

Challenge: Where do I Belong

Link to the challenge:

Modifying the array you are iterating over is generally not a good idea. arr.length changes as you modify the array:

Side note: as a rule of thumb, if you write a for loop but never use the iteration variable, then you don’t actually want to use a for loop.

2 Likes