开发者

JS - How could I count each single element in array?

I would like to know how many element of each number is in array, i. e.: [2,2,3,6,1,1001,2] should return 2 => 3, 3 => 1, 6 = >1, 1 => 1, 1001 => 1. But when I use additional array when I set counted[2] = 3, and counted[1001] = 1 I create 1002 length array (in opposite to arrays in PHP I 开发者_如何学编程think...). How could I improve it? (of course I don't know how many element there will be in my input array) Thanks in advice.


Use a Javascript object as a hashtable, so the numbers are represented as properties on that object:

var array = [2,2,3,6,1,1001,2];
var numbers = {};
for (var i = 0; i < array.length; i++) {
    var number = array[i];
    if (typeof(numbers[number]) === "undefined") {
        numbers[number] = 1;
    } else {
        numbers[number]++;
    }
}


You could use objects.

Here is an example:

var src = [2,2,3,6,1,1001,2]
var results = {}

for (var i = 0, n = src.length; i < n; i++)
{
   results[src[i]] = results[src[i]] || 0
   results[src[i]] += 1
}

// Iterate over results or access by index to see frequency
for (var idx in results)
{
   console.log(idx + " ==> " + results[idx])
}


Try using Object instead of Array.

Array assumes that if you insert an element at index x, then it implies that you want an array of at least x length.


This is a very naive answer, but you could try using a hashmap instead.

var counted = { };
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜