I write this code, for inserting the second argument if any of the array items are bigger than it. but suddenly an infinite loop occurs. ('result.splice(i, 0, num)' causes it) Can anybody tell me why?!
function getIndexToIns(arr, num) {
let result = arr.sort(function(a, b){return a - b})
for(let i = 1; i <= result.length ; i++){
result.splice(i, 0, num)
}
return result;
}
getIndexToIns([40, 60, 20, 0], 50);
arr? What isgetIndexToIns()?i <= result.lengthcondition unreachable.0inspliceyou are adding to the array instead of replacing. To make your code more maintainable create a new array instead of modifing the existing array. There is a rule of thump to never modify the array you are iterating