2017-10-20 150 views
0

我有一个数组,并且需要查找一个字符串有多少匹配。计算数组中的匹配数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); 

回答

2

使用该_.countBy方法。你有一个对象,其中的键 - 它在你的数组和值中串入 - 适当字符串的出现次数。

var arr = ['car','road','car','ripple']; 
 

 
console.log(_.countBy(arr));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

1

在香草JS你可以使用Array#reduce

var array = ['car','road','car','ripple']; 
 

 
var result = array.reduce(function(r, str) { 
 
    r[str] = (r[str] || 0) + 1; 
 

 
    return r; 
 
}, {}); 
 

 
console.log(result);