惯用地找到给定值在数组中出现的次数

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

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

什么是最惯用/优雅的方法?


拉风的咖菲猫
浏览 291回答 3
3回答

HUX布斯

reduce比filter它不仅仅为了计数而建立一个临时数组,在这里更合适。var dataset = [2,2,4,2,6,4,7,8];var search = 2;var count = dataset.reduce(function(n, val) {&nbsp; &nbsp; return n + (val === search);}, 0);console.log(count);在ES6中:let count = dataset.reduce((n, x) => n + (x === search), 0);请注意,使用自定义匹配谓词进行扩展很容易,例如,对具有特定属性的对象进行计数:people = [&nbsp; &nbsp; {name: 'Mary', gender: 'girl'},&nbsp; &nbsp; {name: 'Paul', gender: 'boy'},&nbsp; &nbsp; {name: 'John', gender: 'boy'},&nbsp; &nbsp; {name: 'Lisa', gender: 'girl'},&nbsp; &nbsp; {name: 'Bill', gender: 'boy'},&nbsp; &nbsp; {name: 'Maklatura', gender: 'girl'}]var numBoys = people.reduce(function (n, person) {&nbsp; &nbsp; return n + (person.gender == 'boy');}, 0);console.log(numBoys);{x:count of xs}在javascript中,对所有项目进行计数(即使对象成为对象)非常复杂,因为对象键只能是字符串,因此无法可靠地对具有混合类型的数组进行计数。不过,以下简单的解决方案在大多数情况下仍然可以正常使用:count = function (ary, classifier) {&nbsp; &nbsp; classifier = classifier || String;&nbsp; &nbsp; return ary.reduce(function (counter, item) {&nbsp; &nbsp; &nbsp; &nbsp; var p = classifier(item);&nbsp; &nbsp; &nbsp; &nbsp; counter[p] = counter.hasOwnProperty(p) ? counter[p] + 1 : 1;&nbsp; &nbsp; &nbsp; &nbsp; return counter;&nbsp; &nbsp; }, {})};people = [&nbsp; &nbsp; {name: 'Mary', gender: 'girl'},&nbsp; &nbsp; {name: 'Paul', gender: 'boy'},&nbsp; &nbsp; {name: 'John', gender: 'boy'},&nbsp; &nbsp; {name: 'Lisa', gender: 'girl'},&nbsp; &nbsp; {name: 'Bill', gender: 'boy'},&nbsp; &nbsp; {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) {&nbsp; &nbsp; return item.gender});console.log(countByGender);在ES6中,您可以使用Map对象可靠地计数任意类型的对象。class Counter extends Map {&nbsp; &nbsp; constructor(iter, key=null) {&nbsp; &nbsp; &nbsp; &nbsp; super();&nbsp; &nbsp; &nbsp; &nbsp; this.key = key || (x => x);&nbsp; &nbsp; &nbsp; &nbsp; for (let x of iter) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.add(x);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; add(x) {&nbsp; &nbsp; &nbsp; x = this.key(x);&nbsp; &nbsp; &nbsp; this.set(x, (this.get(x) || 0) + 1);&nbsp; &nbsp; }}// again, with no classifier just count distinct elementsresults = new Counter([1, 2, 3, 1, 2, 3, 1, 2, 2]);for (let [number, times] of results.entries())&nbsp; &nbsp; console.log('%s occurs %s times', number, times);// counting objectspeople = [&nbsp; &nbsp; {name: 'Mary', gender: 'girl'},&nbsp; &nbsp; {name: 'John', gender: 'boy'},&nbsp; &nbsp; {name: 'Lisa', gender: 'girl'},&nbsp; &nbsp; {name: 'Bill', gender: 'boy'},&nbsp; &nbsp; {name: 'Maklatura', gender: 'girl'}];chessChampions = {&nbsp; &nbsp; 2010: people[0],&nbsp; &nbsp; 2012: people[0],&nbsp; &nbsp; 2013: people[2],&nbsp; &nbsp; 2014: people[0],&nbsp; &nbsp; 2015: people[2],};results = new Counter(Object.values(chessChampions));for (let [person, times] of results.entries())&nbsp; &nbsp; console.log('%s won %s times', person.name, times);// you can also provide a classifier as in the abovebyGender = new Counter(people, x => x.gender);for (let g of ['boy', 'girl'])&nbsp; &nbsp;console.log("there are %s %ss", byGender.get(g), g);的类型感知实现Counter可以如下所示(Typescript):type CounterKey = string | boolean | number;interface CounterKeyFunc<T> {&nbsp; &nbsp; (item: T): CounterKey;}class Counter<T> extends Map<CounterKey, number> {&nbsp; &nbsp; key: CounterKeyFunc<T>;&nbsp; &nbsp; constructor(items: Iterable<T>, key: CounterKeyFunc<T>) {&nbsp; &nbsp; &nbsp; &nbsp; super();&nbsp; &nbsp; &nbsp; &nbsp; this.key = key;&nbsp; &nbsp; &nbsp; &nbsp; for (let it of items) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.add(it);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; add(it: T) {&nbsp; &nbsp; &nbsp; &nbsp; let k = this.key(it);&nbsp; &nbsp; &nbsp; &nbsp; this.set(k, (this.get(k) || 0) + 1);&nbsp; &nbsp; }}// example:interface Person {&nbsp; &nbsp; name: string;&nbsp; &nbsp; gender: string;}let people: Person[] = [&nbsp; &nbsp; {name: 'Mary', gender: 'girl'},&nbsp; &nbsp; {name: 'John', gender: 'boy'},&nbsp; &nbsp; {name: 'Lisa', gender: 'girl'},&nbsp; &nbsp; {name: 'Bill', gender: 'boy'},&nbsp; &nbsp; {name: 'Maklatura', gender: 'girl'}];let byGender = new Counter(people, (p: Person) => p.gender);for (let g of ['boy', 'girl'])&nbsp; &nbsp; console.log("there are %s %ss", byGender.get(g), g);

qq_遁去的一_1

较新的浏览器仅由于使用 Array.filtervar dataset = [2,2,4,2,6,4,7,8];var search = 2;var occurrences = dataset.filter(function(val) {&nbsp; &nbsp; return val === search;}).length;console.log(occurrences); // 3

慕雪6442864

这是一次显示所有计数的一种方法:var dataset = [2, 2, 4, 2, 6, 4, 7, 8];var counts = {}, i, value;for (i = 0; i < dataset.length; i++) {&nbsp; &nbsp; value = dataset[i];&nbsp; &nbsp; if (typeof counts[value] === "undefined") {&nbsp; &nbsp; &nbsp; &nbsp; counts[value] = 1;&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; counts[value]++;&nbsp; &nbsp; }}console.log(counts);// Object {//&nbsp; &nbsp; 2: 3,//&nbsp; &nbsp; 4: 2,//&nbsp; &nbsp; 6: 1,//&nbsp; &nbsp; 7: 1,//&nbsp; &nbsp; 8: 1//}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript