我有一个数组:
[1, 2, 3, 5, 2, 8, 9, 2]
我想知道数组中有多少个2。
在JavaScript中,没有for循环的最优雅的方法是什么?
我有一个数组:
[1, 2, 3, 5, 2, 8, 9, 2]
我想知道数组中有多少个2。
在JavaScript中,没有for循环的最优雅的方法是什么?
当前回答
我用这个:
函数countElement(数组,元素){ 令tot = 0; For (var el of array) { If (el == element) { 合计+ +; } } 返回合计; } var arr =(“a”、“b”、“a”,“c”,“d”,“一个”,“e”,“f”,“a”); “a”console.log (countElement (arr));/ / 4
其他回答
这取决于你想如何运行它:
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, …}
我是js数组的reduce函数的开始粉丝。
const myArray =[1, 2, 3, 5, 2, 8, 9, 2];
const count = myArray.reduce((count, num) => num === 2 ? count + 1 : count, 0)
事实上,如果你真的想要花哨一点,你可以在Array原型上创建一个count函数。然后你就可以重复使用了。
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)
一行程序功能
const countBy = (a,f)=>a.reduce((p,v,i,x)=>p+!!f(v,i,x), 0)
countBy([1,2,3,4,5], v=>v%2===0) // 2
为什么需要map或filter呢? Reduce是为这类操作而“诞生”的:
[1、2、3、5、2、8、9、2]。减少((count,2)=>count+(item==val), 0);
就是这样!(如果item==val在每次迭代中,那么1将被添加到累加器计数中,因为true将解析为1)。
作为函数:
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)
}
最好把它包装成函数:
let countNumber = (array,specificNumber) => {
return array.filter(n => n == specificNumber).length
}
countNumber([1,2,3,4,5],3) // returns 1