0

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.

2
  • I think you should use y[x[4]] Commented Jul 11, 2015 at 10:05
  • Why don't you use a Hash? Commented Jul 11, 2015 at 10:08

3 Answers 3

3

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"
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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"

1 Comment

there is no '0' and five in '5' in aaray x in my question, what if ill change the values of x.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.