Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 992
Sergei Basharov Avatar asked Aug 06 '15 10:08

Sergei Basharov


1 Answers

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:

  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex

You may have to shim Array#findIndex if not there, but that's easily done.

like image 187
Ginden Avatar answered Nov 16 '22 19:11

Ginden