Created
November 19, 2024 14:45
-
-
Save Alexander-Pop/135afaa7e96ae47d0edfe49981754f81 to your computer and use it in GitHub Desktop.
JavaScript - Check if an Item Exists in a Multidimensional Array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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