Find the first nonzero index of a value in an array

I have an array of arrays:

[ [0,0], [0,0], [3,2], [5,6], [15,9], [0,0], [7,23], ] 

I could use something like .indexOf(0) if I wanted to find the first index of the zero value, but how to find the index of the first non-zero value, or which meets some criteria?

It may look like .indexOf(function(val){ return val[0] > 0 || val[1] > 0;}) , but this one is not supported.

How can I solve this problem in the most elegant way?

+4
source share
1 answer

How can I solve this problem in the most elegant way?

The best solution is to use your own ES6 .findIndex array method (or Lodash / Underscore _.findIndex ).

 var index = yourArr.findIndex(val=>val[0] > 0 || val[1] > 0) 

This code uses the ES6 arrow function and is equivalent to:

 var index = yourArr.findIndex(function (val) { return val[0] > 0 || val[1] > 0; }); 

Of course, you can use the .some method to retrieve the index, but this solution is not elegant.

Further mention of .find , .findIndex and arrow functions:

You may need to strip Array#findIndex if not, but it is easy to do.

+8
source

All Articles