Why is my array not assigned the value in the for loop?

const sorted = (a, b) =>  a < b ? -1 : a > b ? 1 : 0;

function getIndexToIns(arr, num) {

let newArr = arr.sort(sorted)

let ans = []

for(let i = 0; i < newArr.length; i++){

  if(newArr[i] > num)(

        ans = newArr.splice(i - 1, 0, num))} 

return ans;

}

getIndexToIns([12, 5, 10, 2], 50)

Okay, so a few things:

First, using .splice on an array that you’re looping through will cause weird side-effects, because it’s mutating that array.

Second, .splice returns an array of the items you removed from the array. In your case, you’re not removing any items, so ans is being assigned []. Which… happens to be the value it already has, which is why it looks like it’s not being assigned.

1 Like

It really helps us if you include a link to the challenge and a description of the problem you’re having.

however, I think the answer to my original question was because the condition is not met if every number in the array is less than the num variable that needs to be placed in the array correctly. However, if I add a number into the array that is larger than the num variable my loop becomes infinite. Here is the infinite loop I am getting now:

const sorted = (a, b) =>  a < b ? -1 : a > b ? 1 : 0;

function getIndexToIns(arr, num) {
let newArr = arr.sort(sorted)
let ans = []


for(let i = 0; i < newArr.length; i++){
  
  if(newArr[i] > num){
        ans = newArr.splice(i - 1, 0, num)}
}

return ans;
}

console.log(getIndexToIns([12, 5, 10, 2, 60], 50))

Ahh that makes sense. Thanks. I will attempt a rework accordingly.

It seems I have completely deviated from the original problem, and I am trying to insert the num variable into the sequential order into the array. But If that is what I need to solve I can just push the number in then sort. Really made a mountain into a mole hill on that one. Been working on this one too long.

Your logic up until the for loop is good.
Inside the for loop what I would do is →

1 Check if the newArr[i] is greater than the num and newArr[i-1] is lesser than the num. IF so return the index using indexOf()

2 If newArr[i] is equal to num return the index then and there.

3 If the num is greater than the last element of the newArr , return the total length of the arr (which is one more than the index)

4 In the end, put a return 0 outside the for loop to pass the rest of the cases.

You dont need the ans variable in all this.

Thanks for the help. Really appreciate it.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.