我有一个数组:
[1, 2, 3, 5, 2, 8, 9, 2]
我想知道数组中有多少个2。
在JavaScript中,没有for循环的最优雅的方法是什么?
我有一个数组:
[1, 2, 3, 5, 2, 8, 9, 2]
我想知道数组中有多少个2。
在JavaScript中,没有for循环的最优雅的方法是什么?
当前回答
2017: 如果有人仍然对这个问题感兴趣,我的解决方法如下:
const arrayToCount = [1,2,3,5,2,8,9,2]; const result = arrayToCount。Filter (i => i == 2).length; Console.log('找到的元素数量:' +结果);
其他回答
我是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)
这是javascript中的一行代码。
使用地图。在数组中找到匹配的值(v === 2),返回一个由1和0组成的数组。 使用减少。将该数组的所有值相加,得到所找到的总数。
[1, 2, 3, 5, 2, 8, 9, 2]
.map(function(v) {
return v === 2 ? 1 : 0;
})
.reduce((a, b) => a + b, 0);
结果是3。
递归解
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
如果您正在使用lodash或下划线_。countBy方法将提供一个由数组中的每个值键定的总计的对象。如果你只需要计算一个值,你可以把它变成一行代码:
_.countBy(['foo', 'foo', 'bar'])['foo']; // 2
这也适用于数字数组。示例中的一行代码是:
_.countBy([1, 2, 3, 5, 2, 8, 9, 2])[2]; // 3
不使用循环通常意味着将进程交给一些使用循环的方法。
这里有一个讨厌循环的编码器可以以一定的代价来满足他的厌恶:
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
*/