使用下划线来计算出现次数并填充缺失值

时间:2015-10-21 21:39:23

标签: javascript underscore.js

假设我有一系列介于1和10之间的数字。我想知道每个数字的出现频率。我能做到这一点:

<form class="form-inline">
  <div class="radio-inline">
    <label for="option1">
      <input type="radio" id="option1"> Option 1
    </label>
  </div>
  <div class="radio-inline">
    <label for="option2">
      <input type="radio" id="option2"> Option 2
    </label>
  </div>
  <button type="submit" class="btn btn-primary">Submit</button>
</form>

但是var a = [4,5,6,7,8,9,4,6,8,9,3,5,7,8,4,5,8,4,7]; var b = _.countBy(a, _.identity); 会产生:

console.log(b)

因此缺少Object { //1=0, this is missing //2=0, this is missing 3=1, 4=4, 5=3, 6=2, 7=3, 8=4, 9=2, //10=0 this is missing } 12类别。

使用下划线,如何强制它们被包含在内,其值为零?

2 个答案:

答案 0 :(得分:1)

使用普通的javascript你可以做到

&#13;
&#13;
var array = [4, 5, 6, 7, 8, 9, 4, 6, 8, 9, 3, 5, 7, 8, 4, 5, 8, 4, 7];

var counts = {};

for (var i = 1; i <= 10; i++) {
  counts[i] = 0;
}

array.forEach(function(number) {
  counts[number]++;
});

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

答案 1 :(得分:1)

试试这个

var a = [4,5,6,7,8,9,4,6,8,9,3,5,7,8,4,5,8,4,7],
    obj = {};
_.each(_.range(1, 11), function(item) {
        obj[item] = 0
})
_.each(a, function(item) {
    ++obj[item]; 
});

obj将是:

{
    "1": 0,
    "2": 0,
    "3": 1,
    "4": 4,
    "5": 3,
    "6": 2,
    "7": 3,
    "8": 4,
    "9": 2,
    "10": 0
}