0

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.

3
  • 2
    You're misunderstanding the in operator. Commented Aug 19, 2013 at 20:12
  • s is undefined as well Commented Aug 19, 2013 at 20:16
  • Actually, your code is correct. Please post the complete code, with s and length defined. Commented Aug 19, 2013 at 21:05

1 Answer 1

1

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

Comments

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.