Javascript 计算数组Lodash中的匹配数
我有一个数组,需要找到一个字符串有多少个匹配项Javascript 计算数组Lodash中的匹配数,javascript,lodash,Javascript,Lodash,我有一个数组,需要找到一个字符串有多少个匹配项 Array = ['car','road','car','ripple']; Array.forEach(function(element) { // Here for every element need to see how many there are in the same array. // car = 2 //road = 1 //... }, this); 使用该方法。您
Array = ['car','road','car','ripple'];
Array.forEach(function(element) {
// Here for every element need to see how many there are in the same array.
// car = 2
//road = 1
//...
}, this);
使用该方法。您得到了一个对象,其中键-它是数组中的字符串,值-相应字符串的出现次数
var arr=['car','road','car','ripple'];
控制台日志(u.countBy(arr))代码>
在vanilla JS中,您可以使用:
var数组=['car'、'road'、'car'、'ripple'];
var result=array.reduce(函数(r,str){
r[str]=(r[str]| | 0)+1;
返回r;
}, {});
控制台日志(结果)代码>