Categories
JavaScript Answers

How to search an array of arrays with JavaScript?

Spread the love

Sometimes, we want to search an array of arrays with JavaScript.

In this article, we’ll look at how to search an array of arrays with JavaScript.

How to search an array of arrays with JavaScript?

To search an array of arrays with JavaScript, we can convert the nested arrays to a JSON string and them compare them.

For instance, we write:

const arr = [
  [2, 6, 89, 45],
  [3, 566, 23, 79],
  [434, 677, 9, 23]
];

const arrToFind = [3, 566, 23, 79]
const result = arr
  .map(JSON.stringify)
  .findIndex(a => {
    return a === JSON.stringify(arrToFind)
  })
console.log(result)

to find arrToFind in arr.

To do this, we call arr.map with JSON.stringify to convert each nested array to JSON strings.

Then we call findIndex with a callback that checks if a is the same as the stringified version of arrToFind.

Therefore, we see that result is 1 from the log.

Conclusion

To search an array of arrays with JavaScript, we can convert the nested arrays to a JSON string and them compare them.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *