0

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);
5
  • Where is arr? What is getIndexToIns()? Commented Dec 7, 2020 at 15:59
  • sorry, I edited the code. Commented Dec 7, 2020 at 16:01
  • please add the wanted result. Commented Dec 7, 2020 at 16:02
  • 1
    "if any of the array items are bigger than it" there is nothing in your code that does it. Basically you unconditionally insert new element in array making i <= result.length condition unreachable. Commented Dec 7, 2020 at 16:03
  • if you delete count is 0 in splice you 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 Commented Dec 7, 2020 at 16:05

1 Answer 1

3

Your

result.splice(i, 0, num)

inserts a new value at the index and increments the length of the array.

Beside that, you loop over the last given index, too.

Instead, you could sort and iterate from the end to replace grater values with the maximum wanted value.

function sortAndReplaceGreaterValues([...array], number) {
    array.sort((a, b) => a - b);
    let i = array.length;
    while (i--) {
        if (array[i] < number) break;
        array[i] = number;
    }
    return array;
}

console.log(sortAndReplaceGreaterValues([40, 60, 20, 0], 50));

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

Comments

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.