LVX-001
LVX-001

Reputation: 56

need help understanding using an associative array to keep track of array value appearances

code:

method = function(a) {
//use associative array to keep track of the total number of appearances of a value
//in the array
var counts = [];
for(var i = 0; i <= a.length; i++) {
   if(counts[a[i]] === undefined) {
     //if the condition is looking for a[0],a[1],a[2],a[3],a[4],a[5] inside counts[] one value at a time and does not find them inside counts[] it will set each value to 1 

     counts[a[i]] = 1;
     console.log(counts[a[i]]);
   } else {
       return true;
   }
 }
return false;
}

the js console logs 1x6

how can the condition see if a value inside counts[a[i]] has been repeated if all of the counts[a[i]] values are being set to 1 each iteration? wouldn't it always be comparing 1 to 1?

for example, if the a array is [1,2,3,4,5,2] and counts[a[1]](first int 2 in the array) is undefined and then set to 1, how would the condition know that counts[a[5]](second int 2 in the array) is the same value as counts[a[1]] and therefore it should return true?

perhaps I am misunderstanding whats going on. I would appreciate any help. thanks

Upvotes: 1

Views: 28

Answers (1)

Jonas Wilms
Jonas Wilms

Reputation: 138477

function counter(){
this.counts=[];
}

counter.prototype.add=function(a){
  if(this.counts[a] === undefined) {
    this.counts[a] = 1;
    console.log(this.counts);
   } else {
      return true;
    }
   return false;
 }

try this:

c= new counter();
c.counts;//[]
c.add(1);
c.counts;//[ ,1]
c.add(5);
c.counts;//[ ,1, , , ,1]
c.add(1);//true
...

may it helps you to understand whats going on

Upvotes: 1

Related Questions