52

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

例如,如果我有一个定义为 so: 的数组var dataset = [2,2,4,2,6,4,7,8];,我想查找数组中某个值的出现次数。也就是说,程序应该显示如果我出现了 3 次 value 2,则出现了 1 次 value 6,依此类推。

这样做的最惯用/优雅的方式是什么?

4

11 回答 11

141

reduce在这里更合适,filter因为它不构建临时数组只是为了计数。

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);

console.log(count);

在 ES6 中:

let count = dataset.reduce((n, x) => n + (x === search), 0);

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

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);

console.log(numBoys);

统计所有项目,也就是{x:count of xs}在javascript中制作一个like对象是很复杂的,因为对象键只能是字符串,所以不能可靠地统计一个混合类型的数组。尽管如此,以下简单的解决方案在大多数情况下都可以很好地工作:

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

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'}
];

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

cc = count([1, 2, 2, 2, 3, 1]);
console.log(cc);

// With a `classifier` you can group elements by specific property:

countByGender = count(people, function (item) {
    return item.gender
});
console.log(countByGender);

2017 年更新

在 ES6 中,您使用Map对象来可靠地计算任意类型的对象。

class Counter extends Map {
    constructor(iter, key=null) {
        super();
        this.key = key || (x => x);
        for (let x of iter) {
            this.add(x);
        }
    }
    add(x) {
      x = this.key(x);
      this.set(x, (this.get(x) || 0) + 1);
    }
}

// again, with no classifier just count distinct elements

results = new Counter([1, 2, 3, 1, 2, 3, 1, 2, 2]);
for (let [number, times] of results.entries())
    console.log('%s occurs %s times', number, times);


// counting objects

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


chessChampions = {
    2010: people[0],
    2012: people[0],
    2013: people[2],
    2014: people[0],
    2015: people[2],
};

results = new Counter(Object.values(chessChampions));
for (let [person, times] of results.entries())
    console.log('%s won %s times', person.name, times);

// you can also provide a classifier as in the above

byGender = new Counter(people, x => x.gender);
for (let g of ['boy', 'girl'])
   console.log("there are %s %ss", byGender.get(g), g);

的类型感知实现Counter可以如下所示(Typescript):

type CounterKey = string | boolean | number;

interface CounterKeyFunc<T> {
    (item: T): CounterKey;
}

class Counter<T> extends Map<CounterKey, number> {
    key: CounterKeyFunc<T>;

    constructor(items: Iterable<T>, key: CounterKeyFunc<T>) {
        super();
        this.key = key;
        for (let it of items) {
            this.add(it);
        }
    }

    add(it: T) {
        let k = this.key(it);
        this.set(k, (this.get(k) || 0) + 1);
    }
}

// example:

interface Person {
    name: string;
    gender: string;
}


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


let byGender = new Counter(people, (p: Person) => p.gender);

for (let g of ['boy', 'girl'])
    console.log("there are %s %ss", byGender.get(g), g);
于 2013-06-26T06:56:19.813 回答
42
array.filter(c => c === searchvalue).length;
于 2016-08-25T08:19:50.120 回答
16

这是一次显示所有计数的一种方法:

var dataset = [2, 2, 4, 2, 6, 4, 7, 8];
var counts = {}, i, value;
for (i = 0; i < dataset.length; i++) {
    value = dataset[i];
    if (typeof counts[value] === "undefined") {
        counts[value] = 1;
    } else {
        counts[value]++;
    }
}
console.log(counts);
// Object {
//    2: 3,
//    4: 2,
//    6: 1,
//    7: 1,
//    8: 1
//}
于 2013-06-26T06:56:24.663 回答
12

较新的浏览器仅由于使用Array.filter

var dataset = [2,2,4,2,6,4,7,8];
var search = 2;
var occurrences = dataset.filter(function(val) {
    return val === search;
}).length;
console.log(occurrences); // 3
于 2013-06-26T06:51:16.290 回答
9
const dataset = [2,2,4,2,6,4,7,8];
const count = {};

dataset.forEach((el) => {
    count[el] = count[el] + 1 || 1
});

console.log(count)

//  {
//    2: 3,
//    4: 2,
//    6: 1,
//    7: 1,
//    8: 1
//  }
于 2015-01-04T14:59:15.667 回答
6

使用正常循环,您可以一致且可靠地找到事件:

const dataset = [2,2,4,2,6,4,7,8];

function getNumMatches(array, valToFind) {
    let numMatches = 0;
    for (let i = 0, j = array.length; i < j; i += 1) {
        if (array[i] === valToFind) {
            numMatches += 1;
        }
    }
    return numMatches;
}

alert(getNumMatches(dataset, 2)); // should alert 3

演示: https ://jsfiddle.net/a7q9k4uu/

为了使其更通用,该函数可以接受具有自定义逻辑(返回true/ false)的谓词函数,这将确定最终计数。例如:

const dataset = [2,2,4,2,6,4,7,8];

function getNumMatches(array, predicate) {
    let numMatches = 0;
    for (let i = 0, j = array.length; i < j; i += 1) {
        const current = array[i];
        if (predicate(current) === true) {
            numMatches += 1;
        }
    }
    return numMatches;
}

const numFound = getNumMatches(dataset, (item) => {
    return item === 2;
});

alert(numFound); // should alert 3

演示: https ://jsfiddle.net/57en9nar/1/

于 2013-06-26T06:55:00.860 回答
4

您可以使用 reduce 在一行中计算数组中的所有项目。

[].reduce((a,b) => (a[b] = a[b] + 1 || 1) && a, {})

这将产生一个对象,其键是数组中的不同元素,值是数组中元素的出现次数。然后,您可以通过访问对象上的相应键来访问一个或多个计数。

例如,如果您要将上述内容包装在一个名为的函数中count()

function count(arr) {
  return arr.reduce((a,b) => (a[b] = a[b] + 1 || 1) && a, {})
}

count(['example'])          // { example: 1 }
count([2,2,4,2,6,4,7,8])[2] // 3
于 2017-07-28T21:25:53.253 回答
2

你可以使用array.reduce(callback[, initialValue])方法在JavaScript 1.8

var dataset = [2,2,4,2,6,4,7,8],
    dataWithCount = dataset.reduce( function( o , v ) {

        if ( ! o[ v ] ) {
            o[ v ] = 1 ;  
        }  else {
            o[ v ] = o[ v ] + 1;
        }      

        return o ;    

    }, {} );

// print data with count.
for( var i in  dataWithCount ){
     console.log( i + 'occured ' + dataWithCount[i] + 'times ' ); 
}

// find one number
var search = 2,
    count = dataWithCount[ search ] || 0;
于 2013-06-26T06:57:49.253 回答
1

我发现最终得到一个对象列表更有用,其中包含一个用于计数的键和一个用于计数的键:

const data = [2,2,4,2,6,4,7,8]
let counted = []
for (var c of data) {
  const alreadyCounted = counted.map(c => c.name)
  if (alreadyCounted.includes(c)) {
    counted[alreadyCounted.indexOf(c)].count += 1
  } else {
    counted.push({ 'name': c, 'count': 1})
  }
}
console.log(counted)

返回:

[ { name: 2, count: 3 },
  { name: 4, count: 2 },
  { name: 6, count: 1 },
  { name: 7, count: 1 },
  { name: 8, count: 1 } ]

这不是最干净的方法,如果有人知道如何达到相同的结果,请reduce告诉我。但是,它确实产生了一个相当容易使用的结果。

于 2018-02-08T14:38:16.630 回答
0

如果您尝试以这种方式执行此操作,您可能会收到如下所示的错误。

array.reduce((acc, arr) => acc + (arr.label === 'foo'), 0); // Operator '+' cannot be applied to type 'boolean'.

一种解决方案是这样做

array = [
    { id: 1, label: 'foo' },
    { id: 2, label: 'bar' },
    { id: 3, label: 'foo' },
    { id: 4, label: 'bar' },
    { id: 5, label: 'foo' }
]

array.reduce((acc, arr) => acc + (arr.label === 'foo' ? 1 : 0), 0); // result: 3
于 2021-11-04T14:45:17.083 回答
0

首先,您可以通过使用线性搜索来使用蛮力解决方案。

public int LinearSearchcount(int[] A, int data){
  int count=0;
  for(int i=0;i<A.length;i++) {
    if(A[i]==data) count++;
  }
  return count;
}

但是,为此,我们得到时间复杂度为 O(n)。但是通过二分搜索,我们可以提高复杂度。

于 2018-05-10T08:41:47.247 回答