Reputation: 157
I have this array:
var array = [400, 4000, 400, 400, 4000];
How can I get the index of the first element with value greater than 400?
Note: While making sure this question was unique, I came across questions asking this same problem- but for different programming languages.
If there are duplicates of my question that apply to JS, I'd really want to see them.
Upvotes: 12
Views: 15020
Reputation: 4494
let array = [0, 0, 3, 5, 6];
let x = 5;
let i = 0;
for (; i<array.length && array[i] <= x; i++);
If there is an element greater than x, this returns the index of the first one. Otherwise it returns the length of the array.
Upvotes: 0
Reputation: 13
var array = [0, 0, 3, 5, 6];
var x = 5;
var i = 0;
while (array[i] <= x) {
i++;
}
Upvotes: 0
Reputation: 15501
You can use a simple for
loop and check each element.
var array = [400, 4000, 400, 400, 4000];
var result;
for(var i=0, l=array.length; i<l; i++){
if(array[i] > 400){
result = i;
break;
}
}
if(typeof result !== 'undefined'){
console.log('number greater than 400 found at array index: ' + result);
} else {
console.log('no number greater than 400 found in the given arrry.');
}
Read up: for
- JavaScript | MDN
Upvotes: 5