2017-10-20 145 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);