Find if Item Exists in 2-Dimentional Javascript Array
Example 1 returns true if an element exists in a 2d array, otherwise false
Example 2 returns the 2d array index i.e. [row, col] if found, otherwise false
Problem: indexOf() doesn't work for 2-d Javascript arrays. Here's the one-liner solution.
There are a lot of solutions out there that loop through a 2d array but that's not necessary. Just flatten the array then use indexOf().
The following function converts the 2d array into a single-dimention array, then tests if an item is in it using indexOf(), in one line...
Example 1, returns true or false:
function indexOf2d(array2d, itemtofind) {
return [].concat.apply([], ([].concat.apply([], array2d))).indexOf(itemtofind) !== -1;
}
Given this example 2d array:
array2d = [
["Yes", "sir", "that's", "my", "baby",],
["No", "sir", "don't", "mean", "maybe"]
];
Concat (or flatten) the 2d array to become a single dimentional array:
[].concat.apply([], ([].concat.apply([], array2d))) // flattens the 2d array
The 2d array becomes a single dimention array:
["Yes", "sir", "that's", "my", "baby", "No", "sir", "don't", "mean", "maybe"]
Once you have a single dimentioned array you can use indexOf()
[].concat.apply([], ([].concat.apply([], array2d))).indexOf(itemtofind) !== -1;
indexOf2d(array2d, "boy") // returns -1 or false
indexOf2d(array2d, "baby") // returns 4 or true
​indexOf2d(array2d, "No") // returns 5 or true
Example 2, returns the row and column:
The following function returns the 2d array index, i.e. [row, col] of the location of the found item. The process is similar to above but additionally calculates and returns the row and column, or false if not found.
function indexOf2dArray(array2d, itemtofind) {
index = [].concat.apply([], ([].concat.apply([], array2d))).indexOf(itemtofind);
// return "false" if the item is not found
if (index === -1) { return false; }
// Use any row to get the rows' array length
// Note, this assumes the rows are arrays of the same length
numColumns = array2d[0].length;
// row = the index in the 1d array divided by the row length (number of columns)
row = parseInt(index / numColumns);
// col = index modulus the number of columns
col = index % numColumns;
return [row, col];
}
indexOf2dArray(array2d, "boy") // returns -1 or false
indexOf2dArray(array2d, "baby") // returns [0, 4]
​indexOf2dArray(array2d, "No") // returns [1, 0]