To check if an item exists in a multidimensional array in JavaScript, you typically need to use a nested loop, or modern array methods such as Array.prototype.some(), to traverse each sub-array. Here are several ways to achieve this:
1. Using Nested Loops
The traditional way to check for an item in a multidimensional array is to use nested loops:
const multiArray = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
function itemExists(array, item) {
for (let i = 0; i < array.length; i++) {
for (let j = 0; j < array[i].length; j++) {
if (array[i][j] === item) {
return true;
}
}
}
return false;
}
console.log(itemExists(multiArray, 5)); // Output: true
console.log(itemExists(multiArray, 10)); // Output: false
Output
true false
2. Using Array.prototype.some()
You can use the some() method to check if any sub-array contains the item. This approach is cleaner and more declarative.
const multiArray = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
const itemToFind = 5;
const exists = multiArray.some(subArray => subArray.includes(itemToFind));
console.log(exists); // Output: true
Output
true
Explanation:
some(): This method tests whether at least one element in the array passes the test implemented by the provided function.includes(): This method checks if a given value exists in an array.
3. Using Array.prototype.flat() (for a Simpler Approach)
If you want to search through all elements of a multidimensional array without considering sub-array boundaries, you can first flatten the array using flat() and then check for the item using includes().
const multiArray = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
const itemToFind = 5;
const flattenedArray = multiArray.flat();
const exists = flattenedArray.includes(itemToFind);
console.log(exists); // Output: true
Output
true
Explanation:
flat(): This method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth (default is1).includes(): Used to check for the existence of the item in the flattened array.
4. Using Recursion (For Deeply Nested Arrays)
If you have an arbitrarily deep nested array, you can use recursion to search for the item.
function deepSearch(array, item) {
for (const element of array) {
if (Array.isArray(element)) {
if (deepSearch(element, item)) {
return true;
}
} else if (element === item) {
return true;
}
}
return false;
}
const multiArray = [
[1, [2, 3]],
[4, [5, 6]],
[7, [8, 9]]
];
console.log(deepSearch(multiArray, 5)); // Output: true
console.log(deepSearch(multiArray, 10)); // Output: false
Output
true false
Explanation:
Array.isArray()checks if an element is an array.- The function recursively searches through all nested arrays until it finds the item or exhausts all elements.
Summary:
- Nested loops are useful for basic searches in a structured 2D array.
some()andincludes()provide a more modern and readable approach.flat()andincludes()are useful for flattening and searching simpler multidimensional arrays.- Recursion is effective for arbitrarily deep arrays