0

I have an array of country names and I want to create 2 dimensional array of the names and there count. The array i have is,

names = [Afghanistan,Alaska,Alaska,Alaska,Alaska,Alaska,Argentina,Argentina,British Virgin Islands,British Virgin Islands]

So i want the count of each country in 2 dimensional array. for example i need something like this

country['Afghanistan, 1]
country['Alaska, 5]
country['Argentina, 2]

and so on.

Could someone please help. Thanks

4

3 回答 3

1

这是你要求的:

var nameCounts = {};
for(var i = 0; i < names.length; i++) {
    if(names[i] in nameCounts) {
        nameCounts[names[i]]++;
    } else {
        nameCounts[names[i]] = 1;
    }
}

var country = [];
for(var name in nameCounts) {
    country.push([name, nameCounts[name]]);
}

虽然如果我是你,我会在填充后停下来nameCounts,这是一张从名字到计数的地图。

此外,如果您知道名称按字母顺序排列,您可以优化它,就像在您的示例中一样。

于 2013-10-28T00:14:25.267 回答
0

这是另一种直接创建结果数组的方法:

function getNamesCount(a) {
  var nameIndex = {};
  var results = [];

  for (var i=0, iLen=a.length, name; i<iLen; i++) {
    name = a[i];

    if (!nameIndex.hasOwnProperty(name)) {
      nameIndex[name] = results.length;
      results.push(name, 0);
    }
    results[nameIndex[name] + 1] += 1;
  }
  return results;
}
于 2013-10-28T01:28:15.047 回答
0

关于什么:

names = ["Afghanistan","Alaska","Alaska","Alaska","Alaska","Alaska","Argentina","Argentina","British Virgin Islands","British     Virgin Islands"];

function countWords(o,n){
    o[n]=(o[n])?o[n]+1:1;
    return o; 
};

function makeTuples(obj){
    var tuples=[];
    for(var i in obj){
        tuples.push([i, obj[i]])
    }
    return tuples;
}
console.log(makeTuples(names.reduce(countWords, {})))

这是要玩的小提琴。

有关Array.reduce()查看MDN的文档。

不支持的旧浏览器Array.reduce()应该与UnderscoreJs中的相应实现一起使用

于 2013-10-28T00:27:07.387 回答