# 如何计算数组中的某些元素？

2020/10/24 08:42 · javascript ·  · 0评论

``````[1, 2, 3, 5, 2, 8, 9, 2]
``````

``````var count = 0;
for(var i = 0; i < array.length; ++i){
if(array[i] == 2)
count++;
}
``````

[这个答案有点过时：请阅读编辑内容]

（由于缺少块级作用域，我偶尔只用javascript写for循环，因此，如果您需要捕获或克隆迭代索引或值，则无论如何都必须使用函数作为循环的主体。for-loops通常效率更高，但有时您需要关闭。）

``````[....].filter(x => x==2).length
``````

（我们本来可以写的`.filter(function(x){return x==2}).length`

``````[....].reduce((total,x) => (x==2 ? total+1 : total), 0)
``````

（如果需要优化这段代码，在某些浏览器中，for循环可能会更快。您可以在jsperf.com上进行测试。）

``````[1, 2, 3, 5, 2, 8, 9, 2].count(2)
``````

``````Object.defineProperties(Array.prototype, {
count: {
value: function(value) {
return this.filter(x => x==value).length;
}
}
});
``````

2017编辑

``````Object.defineProperties(Array.prototype, {
count: {
value: function(query) {
/*
Counts number of occurrences of query in array, an integer >= 0
Uses the javascript == notion of equality.
*/
var count = 0;
for(let i=0; i<this.length; i++)
if (this[i]==query)
count++;
return count;
}
}
});
``````

``````class Multiset extends Map {
constructor(...args) {
super(...args);
}
if (!this.has(elem))
this.set(elem, 1);
else
this.set(elem, this.get(elem)+1);
}
remove(elem) {
var count = this.has(elem) ? this.get(elem) : 0;
if (count>1) {
this.set(elem, count-1);
} else if (count==1) {
this.delete(elem);
} else if (count==0)
throw `tried to remove element \${elem} of type \${typeof elem} from Multiset, but does not exist in Multiset (count is 0 and cannot go negative)`;
// alternatively do nothing {}
}
}
``````

``````> counts = new Multiset([['a',1],['b',3]])
Map(2) {"a" => 1, "b" => 3}

> counts
Map(3) {"a" => 1, "b" => 3, "c" => 1}

> counts.remove('a')
> counts
Map(2) {"b" => 3, "c" => 1}

> counts.remove('a')
Uncaught tried to remove element a of type string from Multiset, but does not exist in Multiset (count is 0 and cannot go negative)
``````

ES6更新到JS：

``````// Let has local scope
let array = [1, 2, 3, 5, 2, 8, 9, 2]

// Functional filter with an Arrow function
array.filter(x => x === 2).length  // -> 3
``````

JavaScript中的以下匿名Arrow函数（lambda函数）：

``````(x) => {
const k = 2
return k * x
}
``````

``````x => 2 * x
``````

2017年：

``````const arrayToCount = [1, 2, 3, 5, 2, 8, 9, 2];
const result = arrayToCount.filter(i => i === 2).length;
console.log('number of the found elements: ' + result);``````

``````_.countBy(['foo', 'foo', 'bar'])['foo']; // 2
``````

``````_.countBy([1, 2, 3, 5, 2, 8, 9, 2])[2]; // 3
``````

``````(a.length-(' '+a.join(' ')+' ').split(' '+n+' ').join(' ').match(/ /g).length)+1
``````

• 一个是数组
• n是要在数组中计数的数字

``````var a=[1, 2, 3, 5, 2, 8, 9, 2];

/*  returned value: (Number)
3
*/
``````

``````function countItems(arr, what){
var count= 0, i;
while((i= arr.indexOf(what, i))!= -1){
++count;
++i;
}
return count
}

countItems(a,2)

/*  returned value: (Number)
3
*/
``````

``````const arr = [1, 2, 3, 5, 2, 8, 9, 2];
const counts = {};

arr.forEach((el) => {
counts[el] = counts[el] ? (counts[el] += 1) : 1;
});
``````

``````const countsSorted = Object.entries(counts).sort(([_, a], [__, b]) => a - b);
``````

``````[
[ '2', 3 ],
[ '1', 1 ],
[ '3', 1 ],
[ '5', 1 ],
[ '8', 1 ],
[ '9', 1 ]
]
``````

``````function elementsCount(elementToFind, total, number){
}

var ar = [1, 2, 3, 5, 2, 8, 9, 2];
var elementToFind=2;
var result = ar.reduce(elementsCount.bind(this, elementToFind), 0);
``````

``````var ar = [1, 2, 3, 5, 2, 8, 9, 2];
var elementToFind=2;
var result = ar.reduce(function (elementToFind, total, number){
}.bind(this, elementToFind), 0);
``````

`reduce`这类操作是“天生的”：

`[1, 2, 3, 5, 2, 8, 9, 2].reduce( (count,2)=>count+(item==val), 0);`

``````function countInArray(arr, val) {
return arr.reduce((count,item)=>count+(item==val),0)
}
``````

``````Array.prototype.count = function(val) {
return this.reduce((count,item)=>count+(item==val),0)
}
``````

``````const myArray =[1, 2, 3, 5, 2, 8, 9, 2];
const count = myArray.reduce((count, num) => num === 2 ? count + 1 : count, 0)
``````

``````Array.prototype.count = function(filterMethod) {
return this.reduce((count, item) => filterMethod(item)? count + 1 : count, 0);
}
``````

``````const myArray =[1, 2, 3, 5, 2, 8, 9, 2]
const count = myArray.count(x => x==2)
``````

``````let countNumber = (array,specificNumber) => {
return array.filter(n => n == specificNumber).length
}

countNumber([1,2,3,4,5],3) // returns 1
``````

``````    const arr = ['a', 'a', 'b', 'g', 'a', 'e'];
const count = arr.filter(elem => elem === 'a').length;
console.log(count); // Prints 3
``````

elem ==='a'是条件，用您自己的条件替换。

``````function count(arr, value) {
if (arr.length === 1)    {
return arr[0] === value ? 1 : 0;
} else {
return (arr.shift() === value ? 1 : 0) + count(arr, value);
}
}

count([1,2,2,3,4,5,2], 2); // 3
``````
``````var arrayCount = [1,2,3,2,5,6,2,8];
var co = 0;
function findElement(){
arrayCount.find(function(value, index) {
if(value == 2)
co++;
});
console.log( 'found' + ' ' + co + ' element with value 2');
}``````

``````var arrayCount = [1,2,3,4,5,6,7,8];

function countarr(){
var dd = 0;
arrayCount.forEach( function(s){
dd++;
});

console.log(dd);
}``````

``````// say in app.js
Array.prototype.occurrence = function(val) {
return this.filter(e => e === val).length;
}
``````

``````[1, 2, 4, 5, 2, 7, 2, 9].occurrence(2);
// above line returns 3
``````

1. 使用地图。`(v === 2)`在数组中找到匹配的值，并返回一个由1和0组成的数组。
2. 使用减少。将数组的所有值加到找到的总数中。
``````[1, 2, 3, 5, 2, 8, 9, 2]
.map(function(v) {
return v === 2 ? 1 : 0;
})
.reduce((a, b) => a + b, 0);
``````

``````const reduced = (array, val) => { // self explanatory
return array.filter((element) => element === val).length;
}

console.log(reduced([1, 2, 3, 5, 2, 8, 9, 2], 2));

// 3

const reducer = (array) => { // array to set > set.forEach > map.set
const count = new Map();
const values = new Set(array);
values.forEach((element)=> {
count.set(element, array.filter((arrayElement) => arrayElement === element).length);
});
return count;
}
console.log(reducer([1, 2, 3, 5, 2, 8, 9, 2]));

// Map(6) {1 => 1, 2 => 3, 3 => 1, 5 => 1, 8 => 1, …}
``````

``````var myarray = [];
var count = myarray.length;//return 0

myarray = [1,2];
count = myarray.length;//return 2
``````