我有一个数组:
[1, 2, 3, 5, 2, 8, 9, 2]
我想知道数组中有多少个2。
在JavaScript中,没有for循环的最优雅的方法是什么?
我有一个数组:
[1, 2, 3, 5, 2, 8, 9, 2]
我想知道数组中有多少个2。
在JavaScript中,没有for循环的最优雅的方法是什么?
当前回答
递归解
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
其他回答
这是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。
我能想到的最奇怪的方法是:
(a.length-(' '+a.join(' ')+' ').split(' '+n+' ').join(' ').match(/ /g).length)+1
地点:
A是数组 N是数组中要计数的数字
我的建议,使用while或for循环;-)
另一种方法使用RegExp
Const list = [1,2,3,5,2,8,9,2] Const d = 2; Const counter = (' ${list.join()}, '。match(new RegExp(' ${d}\\, ', 'g')) || []).length console.log(柜台)
步骤如下
使用逗号连接字符串,记住在连接后添加',',这样当要匹配的值位于数组的末尾时,就不会有不正确的值 匹配数字和逗号组合的出现次数 获取匹配项的长度
大多数使用数组函数(如filter)的解决方案都是不完整的,因为它们没有参数化。
这里有一个解决方案,可以在运行时设置要计数的元素。
function elementsCount(elementToFind, total, number){
return total += number==elementToFind;
}
var ar = [1, 2, 3, 5, 2, 8, 9, 2];
var elementToFind=2;
var result = ar.reduce(elementsCount.bind(this, elementToFind), 0);
这种方法的优点是可以很容易地更改函数,例如计算大于X的元素的数量。
还可以将reduce函数声明为内联的
var ar = [1, 2, 3, 5, 2, 8, 9, 2];
var elementToFind=2;
var result = ar.reduce(function (elementToFind, total, number){
return total += number==elementToFind;
}.bind(this, elementToFind), 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, …}