pypypu
pypypu

Reputation: 155

Calculate number of match in array Lodash

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

Answers (2)

Ori Drori
Ori Drori

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

Mikhail Shabrikov
Mikhail Shabrikov

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

Related Questions