Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the index of the first element in an array with value greater than x

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.

like image 690
someGuy Avatar asked Jan 12 '17 00:01

someGuy


2 Answers

You can use findIndex here

check this snippet

var array = [400, 4000, 400, 400, 4000];
var index=array.findIndex(function(number) {
  return number > 400;
});
console.log(index);
like image 51
Geeky Avatar answered Oct 26 '22 00:10

Geeky


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

like image 21
Rahul Desai Avatar answered Oct 25 '22 23:10

Rahul Desai