0

I have a multidimensional array, where I'd like to check if a value is in it.

I tried the code below but it didn't work as intended

How do i check if username is in my multidimensional array?

let matrix = [
  ['Lol'],
  ['MyName'],
  ['Matrix']
];

let username = prompt('Enter Username')

if (matrix.includes(username)) {
  alert('YESSS')
} else {
  alert('no')
}
console.log(username)

3
  • 5
    matrix.flat().includes(username) Commented Aug 17, 2022 at 19:07
  • matrix.some(array => array.includes(username)) Commented Aug 17, 2022 at 19:07
  • includes just simply iterates over array elements and checks equality, it can't know that the items are also arrays Commented Aug 17, 2022 at 19:08

1 Answer 1

1

There are a variety of JavaScript idioms to perform this task.

One option is to flatten the array before running include such as the example Hassam Imam posted.

matrix.flat().includes(username)

Issues will arise however depending on how much data is stored in the multidimensional array.

Another option would be to what Konrad Linkowski suggested and leverage some.

matrix.some(array => array.includes(username))

This has a performance increase as it will stop after finding the first case that matches the provided criteria, but the result is boolean. If you just want to know if the value exists I would recommend this solution.

If you wish to know where in the matrix an element is you will want to use find instead of some as it will provide you the index in which it was found.

matrix.find(arr => array.includes(username));

Though this could get quite complex depending on how many dimensions the array has.

Let me know if you have any questions or would like to stub out what this solution may look like.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.