Sergei Basharov
Sergei Basharov

Reputation: 53850

Find first non-zero value index 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 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?

Upvotes: 6

Views: 7483

Answers (1)

Ginden
Ginden

Reputation: 5316

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.

Upvotes: 13

Related Questions