Comparing a given value with a multidimensional array
I really need your help.
I would like to structure and construct an array like below:
var provinces = [
['Ontario','ON'],
['Quebec','QC'],
['British Columbia','BC'],
['Saskatchewan','SK']
];
then id would like to compare value (x) with my array, i.e .:
var x = 'Ontario'
if (x matches the value in the array list 'provinces') { then let x = ON }
How do you write something like this in javascript?
Thanks a lot and appreciation for your help,
+3
source to share
1 answer
Use a function .filter()
that receives a true / false return condition to extract the yen from the array:
var provinces = [
['Ontario','ON'],
['Quebec','QC'],
['British Columbia','BC'],
['Saskatchewan','SK']
];
var x = "Ontario";
//Find if any array item matches the word
var result = provinces.filter(function(item) {
return item[0] == x;
});
//If there a match, get the second index from the first result from the filter
if(result.length > 0)
x = result[0][1];
alert(x);
0
source to share