I'm looking to create a function that returns a value from a set of arrays based on a particular keyword that appears in the URL.
For example:
var URL = "https://blah.com/BCKM";
var indexCode = URL.split('/').pop();
var choices = [['BCKM', 'Beckham', '7'],['SCHO', 'Scholes', '18'],['YRKE', 'Yorke', '19'],['COLE', 'Cole', '9']]
**find "indexCode" in "choices" arrays, then return**
var name = **second item in array that matches BCKM**
var number = **third item in array that matches BCKM**
$(".name").html(name);
$(".number").html(number);
So if the URL is blah.com/BCKM, the script would look up the var "choices" and return the second and third values and insert them in 2 spans:
<span class="name">Beckham</span>
<span class="number">7</span>
I'd just like to know if this is possible, and if so, if I could be pointed in the right direction.
First of all find child array index which have desire code ( eg. BCKM
). Based upon that find Name
and Number
from child array.
Example:
var URL = "https://blah.com/BCKM";
var indexCode = URL.split('/').pop();
var choices = [
['BCKM', 'Beckham', '7'],
['SCHO', 'Scholes', '18'],
['YRKE', 'Yorke', '19'],
['COLE', 'Cole', '9']
];
function find(choices, code) {
return choices.findIndex(row => row.indexOf(code) !== -1);
}
var ind = find(choices, indexCode); // get index
var name = choices[ind][1];
var number = choices[ind][2];
$(".name").html(name);
$(".number").html(number);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="name"></span> <br/>
<span class="number"></span>