1

I started learning to code & JavaScript nearly two months ago. And I guess I have now a good knowledge of the basics except arrays. I have a big problem with arrays when it comes to iterating and storing ONE single element in a given variable.

For example:

function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  var sorted = arr.sort(function(a, b) {
    return a > b;
  });

  // console.log(sorted);

  var checker = 0;
  var finalResult = 0;

  for (var i = 0; i < sorted.length; i++) {
    checker = num;
    if (checker <= sorted[i]) {
      checker = sorted[i];
      console.log(checker);
      finalResult = arr.indexOf(checker);
    }
  }
    return finalResult;
}



console.log(getIndexToIns([10, 20, 30, 40, 50], 35));

In this example, I want to loop over arr and whenever the if condition is true store that value in the checker variable. But it is storing that value 40 but the loop does not stop, it continues and store the remaining elements in the array also, i.e, 50.

Please explain to me the concept and how to stop the loop and store that single element when the condition is true.

2
  • 1
    You should add a break; in your if to stop the loop. Commented Feb 5, 2018 at 8:59
  • 1
    Array#sort sorts in place, and need not a boolean value, but a value smaller than zero, zero or greater than zero, depending on the wanted order. Commented Feb 5, 2018 at 8:59

2 Answers 2

1

Some annotations

function getIndexToIns(arr, num) {
    var i;                             // declare at top

    arr.sort(function (a, b) {         // sort sorts in situ
        return a - b;                  // return delta, because sort expects
    });                                // numerical values

    for (i = 0; i < arr.length; i++) {
        if (arr[i] >= num) {
            break;                     // exit loop on find
        }
    }
    return i;                          // no need for indexOf, index is known
}

console.log(getIndexToIns([10, 20, 30, 40, 50], 35));
console.log(getIndexToIns([10, 20, 30, 40, 50], 100));

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

Comments

0

You should use a break statement when you want to return from the for loop.

function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  var sorted = arr.sort(function(a, b) {
    return a > b;
  });

  // console.log(sorted);

  var checker = 0;
  var finalResult = 0;

  for (var i = 0; i < sorted.length; i++) {
    checker = num;
    if (checker <= sorted[i]) {
      checker = sorted[i];
      console.log(checker);
      finalResult = arr.indexOf(checker);
      break;
    }
  }
    return finalResult;
}

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.