Yogesh Bhatt
Yogesh Bhatt

Reputation: 127

Javascript: Function returns 0 instead of the number that appears odd number of times

I am trying to solve a challenge from Codewars where you have to find the number in an array that appears odd number of times. I modified my answer to return the number that appears odd number of times and is most frequent. But it always results in 0

counts={};

function findOdd(A) {
    for (var i=0; i<A.length; i++){
      if ((typeof counts["a" + toString(A[i])]) !== 'undefined'){
        counts["a" + toString(A[i])]++;
      }
      else{
        counts["a" + toString(A[i])]=1;
      }
    }

    max = 0;
    for (a in counts){
      if (counts[a]>max && counts[a]%2!==0){
        max = counts[a]
      }
    }

    return max;
}

var testArray=[];

for (var i =0; i<100; i++){
    testArray.push(Math.ceil(Math.random()*100))
}

console.log(findOdd(testArray));

Upvotes: 1

Views: 87

Answers (1)

Evert
Evert

Reputation: 99571

The issue is in toString(). It's not a normal, global function but it actually is a shortcut to window.toString().

You don't actually need toString() for the cases you are using it, Javascript will automatically convert the value to a string for cases like this:

'a' + 5; // equals 'a5'.

Upvotes: 2

Related Questions