计算数组元素的出现次数/频率 [英] Counting the occurrences / frequency of array elements

查看:236
本文介绍了计算数组元素的出现次数/频率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中,我试图获取一个数字值的初始数组并计算其中的元素。理想情况下,结果将是两个新数组,第一个指定每个唯一元素,第二个包含每个元素出现的次数。但是,我愿意接受有关输出格式的建议。

In Javascript, I'm trying to take an initial array of number values and count the elements inside it. Ideally, the result would be two new arrays, the first specifying each unique element, and the second containing the number of times each element occurs. However, I'm open to suggestions on the format of the output.

例如,如果初始数组是:

For example, if the initial array was:

5, 5, 5, 2, 2, 2, 2, 2, 9, 4

然后会创建两个新数组。第一个将包含每个唯一元素的名称:

Then two new arrays would be created. The first would contain the name of each unique element:

5, 2, 9, 4

第二个将包含元素在初始数组中出现的次数:

The second would contain the number of times that element occurred in the initial array:

3, 5, 1, 1

因为号码5在初始数组中出现3次,数字2出现5次,9和4出现一次。

Because the number 5 occurs three times in the initial array, the number 2 occurs five times and 9 and 4 both appear once.

我搜索了很多解决方案,但没有似乎工作,我自己尝试过的所有东西都变得荒谬复杂。任何帮助将不胜感激!

I've searched a lot for a solution, but nothing seems to work, and everything I've tried myself has wound up being ridiculously complex. Any help would be appreciated!

谢谢:)

推荐答案

这里你去:

function foo(arr) {
    var a = [], b = [], prev;

    arr.sort();
    for ( var i = 0; i < arr.length; i++ ) {
        if ( arr[i] !== prev ) {
            a.push(arr[i]);
            b.push(1);
        } else {
            b[b.length-1]++;
        }
        prev = arr[i];
    }

    return [a, b];
}

现场演示: http://jsfiddle.net/simevidas/bnACW/


注意



这会使用 Array.sort

这篇关于计算数组元素的出现次数/频率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆