Skip to content

Instantly share code, notes, and snippets.

@Alexander-Pop
Created November 19, 2024 14:45
Show Gist options
  • Save Alexander-Pop/135afaa7e96ae47d0edfe49981754f81 to your computer and use it in GitHub Desktop.
Save Alexander-Pop/135afaa7e96ae47d0edfe49981754f81 to your computer and use it in GitHub Desktop.
JavaScript - Check if an Item Exists in a Multidimensional Array
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
////////////////////////////////
const itemToFind = 5;
const exists = multiArray.some(subArray => subArray.includes(itemToFind));
console.log(exists); // Output: true
////////////////////////////////
const itemToFind = 5;
const flattenedArray = multiArray.flat();
const exists = flattenedArray.includes(itemToFind);
console.log(exists); // Output: true
////////////////////
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;
}
console.log(deepSearch(multiArray, 5)); // Output: true
console.log(deepSearch(multiArray, 10)); // Output: false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment