user1079065
user1079065

Reputation: 2205

How to find value in 2d array in javascript

this is my code

var text = input.split(" ");
var wordCount = new Array();
var i;
for(i=0; i<text.length; i++){
    if(wordCount.length==0){
        wordCount.push(text[i], 1);
    }
    var index= wordCount.indexOf(text[i]);

so now I have the index of the key and want to find a value corresponding to this key.

I can write a custom sequential method to get the value but is there a shortcut so that I can just say,

var value = wordCount.getValue(text[i]); and that will return 0 or ant other integer

Also push is not making the format as expected, how shall I push key(my word) and its defalut value in the 2d array?

Upvotes: 0

Views: 250

Answers (1)

Navoneel Talukdar
Navoneel Talukdar

Reputation: 4598

Store the corresponding index also with value in the array like this

for(i=0; i < text.length; i++){
if(wordCount.length==0){
    wordCount[i] = text[i];
}

so while retriving value you can do

for(var key in wordCount)
{
  alert("key " + key + " has value " + wordCount[key]);
}

Upvotes: 1

Related Questions