victor
victor

Reputation: 15

How to use an array element as an index of another array

I've two arrays in javascript code. I want to use element of the array x as index for the array y.

You can see I've numbers in the array x, so is there any possible and easy way I can do it.

<script>
    var x = [1,2,3,4,6]
    var y = ["kin","kim","jong","ving","gon","von","rick"]
</script>

like

 y+x[4]  //(not a code just for idea)

must print "rick".

I tried

 y+x[4] //I know that's stupid

but its not working. Please provide answer in javascript.

Upvotes: 0

Views: 74

Answers (3)

blasko
blasko

Reputation: 690

Just pass x[4] as the index to y i.e y[x[4]], which outputs "rick."

Upvotes: 1

Cyzanfar
Cyzanfar

Reputation: 7146

I would use another type of data structure, hashes which stores key value pairs and is appropriate for your use:

var x = { 0: "Kin",
          1: "kim",
          2: "jong",
          3: "vin",
          4: "gon",
          5: "von",
          6: "rich" }

Then to access the data you can do something like this:

x[1] // "kim"

or

x[4] // "gon"

Upvotes: 0

SK.
SK.

Reputation: 4358

You should read about MDN - Array more.

var x = [1,2,3,4,6]
var y = ["kin","kim","jong","ving","gon","von","rick"]
var index = x[4]; //6
console.log(y[index]); // at index 6, value is "rick"

Or

y[x[4]] // "rick"

Upvotes: 3

Related Questions