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
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);
}
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..
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;
}, {});
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.