我有一个数组:
[1, 2, 3, 5, 2, 8, 9, 2]
我想知道数组中有多少个2。
在JavaScript中,没有for循环的最优雅的方法是什么?
我有一个数组:
[1, 2, 3, 5, 2, 8, 9, 2]
我想知道数组中有多少个2。
在JavaScript中,没有for循环的最优雅的方法是什么?
当前回答
我相信你们在寻找的是功能方法
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
为什么需要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)
}
有很多方法可以找到答案。我认为最简单的方法是使用es6中引入的数组过滤器方法。
function itemCount(array, item) {
return array.filter(element => element === item).length
}
const myArray = [1,3,5,7,1,2,3,4,5,1,9,0,1]
const items = itemCount(myArray, 1)
console.log(items)
这取决于你想如何运行它:
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 a=[1, 2, 3, 5, 2, 8, 9, 2];
alert(String(a).replace(/[^2]+/g,'').length);
/* returned value: (Number)
3
*/
如果indexOf作为数组方法可用,还可以重复调用indexOf,并每次移动搜索指针。
这不会创建一个新的数组,并且循环比forEach或过滤器更快。
如果你有一百万个会员可以查看,那就会有所不同。
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
*/