Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Search 2D array for matching variable

This should be easy but my brain is fried.

I have a variable, and I want to search a 2D array that corresponds to matching value:

const fruits = [
["bananas", 123],
["strawberries", 456],
["kiwi", 789],
["mango", 098],
["apple", 543],
];

const input = "apple";

// result should be 543

What would be the shortest way to do so?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

One solution would be to use the find() method to search for the matching value in your array.

For example:

const fruits = [
  ["bananas", 123],
  ["strawberries", 456],
  ["kiwi", 789],
  ["mango", 098],
  ["apple", 543],
];


const input = "apple";

const result = fruits.find(fruit => fruit[0] === input)?.[1];

console.log(result); // 543
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading