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

例如,如果初始数组是:

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

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

5, 2, 9, 4

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

3, 5, 1, 1

因为数字5在初始数组中出现了三次,数字2出现了五次,9和4都出现了一次。

我一直在寻找解决方案,但似乎没有一个可行,而且我自己尝试过的每件事最后都出奇地复杂。任何帮助都将不胜感激!

谢谢:)


当前回答

如果使用下划线或lodash,这是最简单的事情:

_.countBy(array);

这样:

_.countBy([5, 5, 5, 2, 2, 2, 2, 2, 9, 4])
=> Object {2: 5, 4: 1, 5: 3, 9: 1}

正如其他人指出的那样,然后可以对结果执行_.keys()和_.values()函数,以分别获得唯一的数字及其出现次数。但根据我的经验,原始对象更容易处理。

其他回答

查看下面的代码。

<html>
<head>
<script>
// array with values
var ar = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];

var Unique = []; // we'll store a list of unique values in here
var Counts = []; // we'll store the number of occurances in here

for(var i in ar)
{
    var Index = ar[i];
    Unique[Index] = ar[i];
    if(typeof(Counts[Index])=='undefined')  
        Counts[Index]=1;
    else
        Counts[Index]++;
}

// remove empty items
Unique = Unique.filter(function(){ return true});
Counts = Counts.filter(function(){ return true});

alert(ar.join(','));
alert(Unique.join(','));
alert(Counts.join(','));

var a=[];

for(var i=0; i<Unique.length; i++)
{
    a.push(Unique[i] + ':' + Counts[i] + 'x');
}
alert(a.join(', '));

</script>
</head>
<body>

</body>
</html>
function countOcurrences(arr){
    return arr.reduce((aggregator, value, index, array) => {
      if(!aggregator[value]){
        return aggregator = {...aggregator, [value]: 1};  
      }else{
        return aggregator = {...aggregator, [value]:++aggregator[value]};
      }
    }, {})
}

我知道这个问题是旧的,但我意识到有太少的解决方案,你得到的计数数组要求用最小的代码,所以这是我的

// The initial array we want to count occurences
var initial = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4];  

// The count array asked for
var count = Array.from(new Set(initial)).map(val => initial.filter(v => v === val).length);  

// Outputs [ 3, 5, 1, 1 ]

你可以从初始数组中得到集合

var set = Array.from(new Set(initial));  

//set = [5, 2, 9, 4]  

使用MAP,您可以在输出中有两个数组:一个包含出现次数,另一个包含出现次数。

常量数据集=(2、2、4、2、6、4、7、8、5、6、7、10、10、10、15); Let values = []; Let keys = []; var mapwithoccurs = dataset.reduce((a,c) => { 如果(a.has (c)) a.set (c, a.get (c) + 1); 其他a.set (c, 1); 返回一个; }, new Map()) .forEach((value, key, map) => { keys.push(关键); values.push(价值); }); console.log(键) console.log(值)

我在codewars上解决了一个类似的问题,并设计了以下解决方案。

这将给出数组中整数的最高计数以及整数本身。我认为它也可以应用于字符串数组。

要正确地对字符串排序,请从sort()部分中删除函数(a, b){return a-b}

function mostFrequentItemCount(collection) {
    collection.sort(function(a, b){return a-b});
    var i=0;
    var ans=[];
    var int_ans=[];
    while(i<collection.length)
    {
        if(collection[i]===collection[i+1])
        {
            int_ans.push(collection[i]);
        }
        else
        {
            int_ans.push(collection[i]);
            ans.push(int_ans);
            int_ans=[];
        }
        i++;
    }

    var high_count=0;
    var high_ans;

    i=0;
    while(i<ans.length)
    {
        if(ans[i].length>high_count)
        {
            high_count=ans[i].length;
            high_ans=ans[i][0];
        }
        i++;
    }
    return high_ans;
}