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);
}
++, you need to initialize the values to0. Otherwise, you're doingnull+1, which is NaN (not a number). You can solve this by adding that at the beginning of yourforloop:if(!map.hasOwnProperty(arr[i])){ map[arr[i]] = 0; }