Jared Joke
Jared Joke

Reputation: 1356

Javascript for loop not appending list in dictionary

And I'm not sure I understand the problem at all.

var vtf=[]; // Dictionary that maps number-> list
var length;
var s; // A list of numbers with s.length = length
// length and s are set to values

for(i=0; i<length; i++)
{
    var f=s[i]; 
    if(f in vtf)
       vtf[f].push(i);
    else
       vtf[f]=[i];
}

So basically I check if vtf contains the value f=s[i]. If it does it appends i to the list contained at vtf[f] and if it doesn't it makes a new list with i as its only element.

The problem I get is that after running this every index of vtf only contains that first i that was added despite me knowing that almost every value saved in vtf should have a list of multiple elements.

I can't understand what I'm doing wrong. When I put alerts inside the if statement they don't even pop up but when I put them outside the loop, for the same value, they show it's evaluating to true a number of times.

Upvotes: 0

Views: 114

Answers (1)

georg
georg

Reputation: 214969

Your code is correct, the only thing, vtf should be declared as an object, not as an array:

var vtf={};
var s=[1,2,3,4,1,2,3,4]; 

for(i=0; i<s.length; i++)
{
    var f=s[i]; // All values in s are numbers
    if(f in vtf)
       vtf[f].push(i);
    else
       vtf[f]=[i];
}
console.log(JSON.stringify(vtf))

Result:

"{"1":[0,4],"2":[1,5],"3":[2,6],"4":[3,7]}"

Upvotes: 1

Related Questions