Reputation: 155
I have an array, and need to find how many matches of a string are.
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);
Upvotes: 2
Views: 832
Reputation: 191976
In vanilla JS you can use 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);
Upvotes: 1
Reputation: 8509
Use _.countBy
method for that. You got an object, where keys - it strings in your array and values - the number of occurrences for the appropriate string.
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>
Upvotes: 2