Search code examples
javascriptlodash

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);

Solution

  • 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>