Wild Widow
Wild Widow

Reputation: 2549

count the occurances of elements in an array in javascript

I have an array like this, I want to count the frequency of each element

var arr = [1, 5, 7, -1];
function countArray (arr){
    var map = [];
    for (var i =0; i < arr.length ; i++){
        map[arr[i]]++;
    }
    console.log(map);  
}

The console.log prints [1: NaN, 5: NaN, 7: NaN, -1: NaN]

I expected it to print [1: 1, 5: 1, 7: 1, -1: 1]

I do not understand why I'm getting NaN

Upvotes: 1

Views: 119

Answers (4)

Ryan
Ryan

Reputation: 14649

Well, if it was the first occurance, then you would try to increment an undefined. So first check if it is undefined then assign 0, or increment it.

And you should use an Object, not an array. The object has a key and value whereas an Array is an ordered set of elements, accessed by their numeric index.

I'm editing this to explain that you can use an Array Object. If the value of the index is greater than largest index in the array, then it will be resized. However, I think an Object is better to use because in the future if you use some other type of key, (not a Number) then the code won't need any changes.

var arr = [1, 5, 7, -1];
function countArray (arr) {
    var map = {};
    for ( var i =0; i < arr.length ; i++ ){
        map[ arr[i] ] = typeof map[ arr[i] ]  === 'undefined' ? 1 : ++map[ arr[i] ];
    }
    console.log(map);  
}

Upvotes: 4

omarjmh
omarjmh

Reputation: 13888

A more explanatory version (JSBin) with reduce:

var arr = [1, 5, 7, -1];    

var count = arr.reduce(function(obj, next) {
  obj[next] = ++obj[next] || 1;
  return obj;
}, {});

Upvotes: 2

maioman
maioman

Reputation: 18734

Your function is fine but you can do it with array.reduce one liner:

var arr = [1, 5, 7, -1, 1,1];

var r = arr.reduce((ac, x) => { if (!ac[x]) ac[x] = 0;  return ac[x]++, ac},{});

document.write(JSON.stringify(r))

choose whatever you find more readable..

Upvotes: 2

vmg
vmg

Reputation: 10566

You should check if array already contains key, you can use "in" to do that.

var arr = [1, 5, 7, -1, -1];
function countArray (arr){
    var map = [];
    for (var i =0; i < arr.length ; i++){
        if (arr[i] in map) map[arr[i]]++;
        else map[arr[i]] = 1;
    }
    console.log(map);  
}
countArray (arr)

Output:

[1: 1, 5: 1, 7: 1, -1: 2]

Upvotes: 0

Related Questions