计算Lodash数组中的匹配数

时间:2017-10-20 13:05:52

标签: javascript 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 个答案:

答案 0 :(得分: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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

在vanilla JS中,您可以使用Array#reduce

&#13;
&#13;
var array = ['car','road','car','ripple'];

var result = array.reduce(function(r, str) {
  r[str] = (r[str] || 0) + 1;

  return r;
}, {});

console.log(result);
&#13;
&#13;
&#13;