发现发生次数的给定值具有以阵列 [英] Find the number of occurrences a given value has in an array

查看:168
本文介绍了发现发生次数的给定值具有以阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有重复值的数组。我想找到出现的次数为任何给定值。

I have an array with repeating values. I would like to find the number of occurrences for any given value.

例如,如果我有被定义为这样一个数组: var数据集= [2,2,4,2,6,4,7,8]; ,我想找到该阵列在一定值的出现的次数。也就是说,程序应该表明,如果我有3个出现值 2 ,1次价值 6 ,等

For example, if I have an array defined as so: var dataset = [2,2,4,2,6,4,7,8];, I want to find the number of occurrences of a certain value in the array. That is, the program should show that if I have 3 occurrences of the value 2, 1 occurrence of the value 6, and so on.

推荐答案

减少是比较合适的,这里比过滤因为它不建立一个临时数组只是计数。

reduce is more appropriate here than filter as it doesn't build a temporary array just for counting.

var dataset = [2,2,4,2,6,4,7,8];
var search = 2;
var count = dataset.reduce(function(n, val) {
    return n + (val === search);
}, 0);

请注意,很容易扩展,要使用自定义匹配predicate,例如,计算具有特定属性的对象:

Note that it's easy to extend that to use a custom matching predicate, for example, to count objects that have a specific property:

people = [
    {name: 'Mary', gender: 'girl'},
    {name: 'Paul', gender: 'boy'},
    {name: 'John', gender: 'boy'},
    {name: 'Lisa', gender: 'girl'},
    {name: 'Bill', gender: 'boy'},
    {name: 'Maklatura', gender: 'girl'}
]

var numBoys = people.reduce(function(n, person) {
    return n + (person.gender == 'boy');
}, 0);

计数的所有项目,也就是使一个对象如 {X:XS计数} 在JavaScript是复杂的,因为对象键只能是字符串,这样你就可以'T可靠计数混合类型的数组。不过,下面这个简单的解决方案将在大多数情况下工作得很好:

Counting all items, that is, making an object like {x:count of xs} is complicated in javascript, because object keys can only be strings, so you can't reliably count an array with mixed types. Still, the following simple solution will work well in most cases:

count = function(ary, classifier) {
    return ary.reduce(function(counter, item) {
        var p = (classifier || String)(item);
        counter[p] = counter.hasOwnProperty(p) ? counter[p] + 1 : 1;
        return counter;
    }, {})
}

如果你不提供分类这只是计算不同的元素:

If you don't provide a classifier this simply counts different elements:

> count([1,2,2,2,3,1])
{
 "1": 2,
 "2": 3,
 "3": 1
}

随着分类特定属性,你组元素:

> countByGender = count(people, function(item) { return item.gender })
{
 "girl": 3,
 "boy": 3
}

这篇关于发现发生次数的给定值具有以阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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