Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a two dimensional array includes a string?

I have a two dimensional array arr[cols][rows]. I want to know if the cols contains a string "hello". How can I check that using .includes("hello") method.

Please note that I am trying to check this inside a loop with counter i. So I have to do something like arr[i][0].includes("hello");

like image 402
DarthWader Avatar asked Jan 31 '18 08:01

DarthWader


People also ask

How do you find the elements of a 2D array?

An element in 2-dimensional array is accessed by using the subscripts. That is, row index and column index of the array. int x = a[1,1]; Console.


1 Answers

You can use array.prototype.some along with array.prototype.includes. It shoud be:

var datas= [
  ["aaa", "bbb"],
  ["ddd", "eee"]
];

function exists(arr, search) {
    return arr.some(row => row.includes(search));
}

console.log(exists(datas, 'ddd'));
console.log(exists(datas, 'xxx'));
like image 181
Faly Avatar answered Nov 14 '22 22:11

Faly