Mark Kramer
Mark Kramer

Reputation: 3214

Best way to search the the second array in a multidimensional array

I have a grid of values, represented by a two-dimensional array.

Here is a literal representation of the data: dataValues[row][column]

So dataValues[3][0] would be the fourth row, first column.

Well, I need to search the first column of every row for a value and I'm looking for the least computational intensive way of doing that.

I know I can do it with a loop:

for (var i in dataValues) {
  if (dataValues[i][0] == "Totals") {
    matchingRow = i;
    break;
  }
}

But I like to avoid loops wherever possible and I can't think of a way to apply Array.prototype.indexOf in a useful way here.

Is there even a computational difference between a loop and indexOf? It seems to me that indexOf would probably just run its own loop.

Upvotes: 0

Views: 32

Answers (1)

charlietfl
charlietfl

Reputation: 171679

You can use Array#find() which will break once condition is met and return first matching element or return undefined if condition is not met

let matchingItem = dataValues.find(arr=> arr[0] == "Totals");
if(matchingItem ){
  // do what you want with matching elemnt of dataValues
}

Upvotes: 1

Related Questions