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?
3
Answers
You can use
find()
orfilter()
depending on how many results you expect.In case there are no results,
find()
returnsundefined
andfilter()
returns an empty list, so it’s easy to check for results.Another way, better suited if you want to do multiple lookups is to convert the 2D array to a JS object (using
Object.fromEntries()
) or Map which can do lookups more efficiently in constant timeO(1)
as opposed to linear timeO(n)
.One solution would be to use the
find()
method to search for the matching value in your array.For example:
It would be better to convert your array from Google Sheets into an object like this: