0

Assuming the Array is sorted I am trying to find the lowest index of a number to be inserted.

When I log the results to the console in the If statement it appears correct.

However, when I try and log the function to the console I get Undefined?

I have tried to declare the function as a var with similar results.

function lowestIndexInsert(num, arrayofIntegers) {
  arrayofIntegers.forEach(function(element) {
  if(num >= element) {
    // console.log(arrayofIntegers.indexOf(element) + 1)
  return (arrayofIntegers.indexOf(element) + 1);

    }
  });
}
var testarray = [1, 3, 5, 6, 7, 11, 13, 50]

console.log(lowestIndexInsert(35, testarray))

This should display the number 7 to the console instead I get undefined.

1 Answers1

1

lowestIndexInsert() is not returning anything, your return is inside the forEach loop.

Hence the undefined. Try something like this:

function lowestIndexInsert(num, arrayofIntegers) {
  var idx = 0;
  arrayofIntegers.forEach(function(element) {
    if (num >= element) {
      idx = arrayofIntegers.indexOf(element) + 1
    }
  });
  return idx;
}
var testarray = [1, 3, 5, 6, 7, 11, 13, 50]

console.log(lowestIndexInsert(35, testarray))
Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43
  • Or rather, just don't use `forEach`. – Bergi Jul 26 '19 at 16:34
  • This is basically right but I think will find that *last* index that satisfies the condition `num >= element` (because it will keep going and overwrite `idx` with later matches) whereas the OP seems to intend that it stop after the first element. – apsillers Jul 26 '19 at 16:34
  • @apsillers that is a good point, but I dont think it will matter as the array is sorted from least to greatest so it will never become true again. "Assuming the array is sorted" – Veryangrymonk Jul 26 '19 at 16:41