0
var myarr = new Array([001,"Ravi",800000],[002,"John",700000],[003,"Vishal","500000"],
                      [004,"Michel",600000],[005,"Stella",700000]);

How to display one array from myarr? For example if I enter 002 in input box it should display: 002,"John",700000

2
  • Can you change your original data structure to a map? As it stands now, I think you'll have to iterate over the entire array and then check to see if an entry matches. Commented Apr 2, 2017 at 3:07
  • 1
    problem I see is that the first element in each array will be 1,2,3,4,5 not 001, 002, 003, 004, 005 ... because numbers - it'll make the search less obvious to someone who doesn't know how the basics of javascript work Commented Apr 2, 2017 at 3:10

2 Answers 2

2

I would recommend changing your data structure to something resembling a map. Then you can print out each person's data using the number (or string representation thereof) as a key. Something like this:

var data = {};
data["001"] = ["Ravi", 800000];
data["002"] = ["John", 700000];
data["003"] = ["Vishal", 500000];
data["004"] = ["Michel", 600000];
data["005"] = ["Stella", 700000];

var input = "002";
console.log(data[input]);

Demo here:

Rextester

Sign up to request clarification or add additional context in comments.

1 Comment

print()? Why introduce a non-standard function? console.log() works nicely with an embedded, runnable snippet directly in your answer...
-1

This is a classic example of Arrays inside an array.

If you want to display the entire array 002,"John",700000 then take an index of that array from the outer array.

e.g.

<html>
<body>

<p id="demo"></p>

<script>
var myarr = new Array([001,"Ravi",800000],[002,"John",700000],[003,"Vishal","500000"],[004,"Michel",600000],[005,"Stella",700000]);

//This will display your entire second array.
document.getElementById("demo").innerHTML = myarr[1];

</script>

</body>
</html>

If you want a lookup to try key-value data structure in which your id will be key and the entire object will be value.

e.g. var obj = {key1: value1, key2: value2};

1 Comment

"If you want a lookup" - Which is what the question is asking for, so shouldn't that be the focus of the answer?

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.