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.
break;in yourifto stop the loop.Array#sortsorts in place, and need not a boolean value, but a value smaller than zero, zero or greater than zero, depending on the wanted order.