Sunny Noeun
Sunny Noeun

Reputation: 31

Have integer added to end of array if larger than rest of integers in array

My function goes through an array to find the lowest index it should be inserted into. I am assuming the array is always sorted. It works unless the integer is larger than the rest of the array integers. At this point, it needs to be added to the end of the array.

I tried to use if else statements and have the number appended with a push but it just goes into a never-ending loop since I will always stay less than arr.length. I tried adding a break after the push inside the else but then, it always appends without inserting into the correct position if there is a place inside the array for it already.

function lowestIndexInsert(num,arr){
  for (i = 0; i<arr.length; i++){
      if (arr[i]>num){
      arr[i]=num;
      }
      else { 
        arr.push(num);
        break;
      }

  }
 return arr.indexOf(num);
}


lowestIndexInsert(15,[8,25,33,52,70]);// should return 1
lowestIndexInsert(80,[8,25,33,52,70]);// should return 5

Upvotes: 0

Views: 162

Answers (3)

R10t--
R10t--

Reputation: 829

You can use splice to insert an element to the array and then instantly break. Once this is done you can catch the final case where i = length and hasn't been inserted yet. If you use 3 arguments such as: .splice(start, deleteCount, insertMe) the function will insert the item at the specific index and delete none. With this you can do:

function lowestIndexInsert(num,arr){
  for (i = 0; i<arr.length; i++){
      if (arr[i]>num){
          arr.splice(i, 0, num);
          // Break here to stop the loop after inserting
          break;
      }

      // Perform a final check to see if the item was inserted.
      if(i == (arr.length - 1)){
          arr.push(num);
      }

  }
 return arr.indexOf(num);
}


lowestIndexInsert(15,[8,25,33,52,70]);// should return 2
lowestIndexInsert(80,[8,25,33,52,70]);// should return 5

Upvotes: 1

IceMetalPunk
IceMetalPunk

Reputation: 5566

You're pushing inside the loop, so you'll get your new value pushed once for every single number in the array that's greater than the value. That's not what you want.

You can greatly simplify this code, and avoid manual loops altogether:

function lowestIndexInsert(num,arr) {
    let index = arr.length;
    arr.some((value, i) => {
        if (value > num) {
          index = i;
          return true;
        }
        return false;
    });
    arr[index] = num;
}

Upvotes: 0

Scott Hunter
Scott Hunter

Reputation: 49920

If you want to iterate as many times as the original array was long, you have to remember what that length was. That's what variable are for.

Also, you don't know if you need to add to the array until you have finished searching it.

Upvotes: 0

Related Questions