简体   繁体   中英

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

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> 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM