简体   繁体   English

计算事件的发生并将结果存储在使用javascript的键值对中

[英]calculate the occurence and store the result in a key value-pair using javascript

I need to calculate the occurence of the name in an array. 我需要计算名称在数组中的出现。

var eachAuthorData = ["bob","joke","hello","stack","stack","ok","joke","bob"];

I can do this by using a for loop,and get a result like this 我可以通过使用for循环来做到这一点,并得到这样的结果

{bob: 2, joke: 2, hello: 1, stack: 2, ok: 1}

but the result can only be access using 但结果只能是使用

counts["bob"]

not only do I need to know the occrence of each name. 我不仅需要知道每个名字的出现。 but also need to know how many diffent name in the array eachAuthorData how do I locate bob in the eachAuthorData I only need to use the name once 但还需要知道数组eachAuthorData中有多少个不同的名称我如何在eachAuthorData中找到bob我只需要使用一次名称

If you start with an array: 如果以数组开头:

var eachAuthorData = ["bob","joke","hello","stack","stack","ok","joke","bob"];

and you want to know how many of each name there is in the array and how many unique strings there are, you can do it like this: 并且您想知道数组中每个名称有多少个,以及有多少个唯一的字符串,可以这样做:

var counts = {}, i, item, uniques = 0;
for (i = 0; i < eachAuthorData.length; i++) {
    item = eachAuthorData[i];
    if (!counts.hasOwnProperty(item)) {
        counts[item] = 1;
        ++uniques;
    } else {
        ++counts[item];
    }
}

This will generate an output in counts like this: 这将产生如下counts的输出:

{bob: 2, joke: 2, hello: 1, stack: 2, ok: 1}

And, since you asked a few other questions in comments, I added the variable uniques which gives you the total unique string count. 并且,由于您在注释中提出了其他一些问题,因此我添加了变量uniques ,该变量为您提供了总的唯一字符串数。

And, you would access any individual count like this: 并且,您将访问任何单个计数,如下所示:

var cnt = counts["bob"];

Or, if the desired key is in a variable named key , you would use: 或者,如果所需的键在名为key的变量中,则可以使用:

var cnt = counts[key];

If you want to iterate all the counts of all the unique strings, you can do that like this: 如果要迭代所有唯一字符串的所有计数,则可以这样进行:

for (var item in counts) {
    // item is the key
    // counts[item] is the count
    console.log("counts[" + item + "] = " + counts[item]);
}

Working demo: http://jsfiddle.net/jfriend00/eJyAg/ 工作演示: http : //jsfiddle.net/jfriend00/eJyAg/


If you want a list of the keys in the counts object (eg the unique strings), you can use: 如果要获取counts对象中键的列表(例如,唯一字符串),可以使用:

var keys = Object.keys(counts);

Object.keys() requires IE9 or greater or there's a polyfill here if you want interoperability with older versions of IE. Object.keys()需要IE9或更高版本,或者如果您想与IE的较早版本进行互操作,请在此处使用polyfill。

I think you should have: 我认为您应该具有:

var eachAuthorData = ["bob","joke","hello","stack","stack","ok","joke","bob"];

do this to count: 这样做计算:

var toMatch, i, count;

toMatch = "bob";
count   = 0;

for( i=0 ; i<eachAuthorData.length ; ++i ){
  if( eachAuthorData[i] == toMatch ){
    ++count;
  }
}

console.log("The element "+ toMatch +" is counted "+ count +" times!");

Try this one 试试这个

var tempObject = new Object();
function count() {
    array_elements = ["bob","joke","hello","stack","stack","ok","joke","bob"];

    array_elements.sort();

    var current = null;
    var cnt = 0;
    for (var i = 0; i < array_elements.length; i++) {
        if (array_elements[i] != current) {
            if (cnt > 0) {
                tempObject[current]=cnt;
                console.log(current + ' comes --> ' + cnt + ' times<br>');
            }
            current = array_elements[i];
            cnt = 1;
        } else {
            cnt++;
        }
    }
    if (cnt > 0) {
        console.log(current + ' comes --> ' + cnt + ' times');
       tempObject[current]=cnt;
    }

}

count();
console.log(JSON.stringify(tempObject));

Presumably you meant an array like: 大概你的意思是这样的数组:

var data = ["bob","joke","hello","stack","stack","ok","joke","bob"];

Since others have gone the obvious route, I'll post something a little more robust that accounts for the possibility that the data array has elided members (ie is sparse): 由于其他人走了明显的路,我将发布一些更健壮的方法,以说明数据数组已删除成员的可能性(即稀疏):

function countMembers(dataArray) {

  for (var i=0, iLen=dataArray.length, o={}, item; i<iLen; i++) {
    item = dataArray[i];

    if (dataArray.hasOwnProperty(i)) {
       if (o.hasOwnProperty(item)) {
          ++o[item];
       } else {
          o[item] = 1;
       }
    } 
  }
  return o;
}

Given: 鉴于:

["bob","joke",,,,"hello","stack","stack","ok","joke","bob"];

others will include a member undefined: 3 , but the above wont. 其他将包括一个undefined: 3成员undefined: 3 ,但是上面没有。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM