计数的JavaScript数组元素的出​​现 [英] Counting the occurrences of JavaScript array elements

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

问题描述

在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的初始阵列中出现三次,数字2发生五次,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.

我搜索了很多解决的办法,但似乎没有任何工作,一切我已经试过自己已经清盘是可笑的复杂。任何帮助将是AP preciated!

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/

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

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