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 first zero value index, but how do I find index of the first non-zero value or which conforms to some criteria?
It might look like .indexOf(function(val){ return val[0] > 0 || val[1] > 0;})
, but this one is not supported.
How do I tackle this problem in the most elegant way?
How do I tackle this problem in the most elegant way?
The best solution is to use native ES6 array method .findIndex
(or Lodash/Underscore _.findIndex
).
var index = yourArr.findIndex(val=>val[0] > 0 || val[1] > 0)
This code uses ES6 arrow function and is equivalent to:
var index = yourArr.findIndex(function (val) {
return val[0] > 0 || val[1] > 0;
});
You can of course use .some
method to retrieve index, but this solution isn't elegant.
Further reference about .find
, .findIndex
and arrow functions:
You may have to shim Array#findIndex
if not there, but that's easily done.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With