underscore js - 出现次数超过一定次数的项目列表

underscore js - list of items that occur above a certain number of times

我正在尝试获取出现次数超过特定次数的项目列表。以下代码从对象数组中提取 ID。然后过滤掉那些出现两次或更多次的项目。

item[1] 是出现次数,item[0] 是学号。

var list = _.chain(allpeople)
    .countBy(function(regentry) {
        return regentry.get("Student").id;
    })
    .pairs()
    .filter(function(item){
        if(item[1]>=2)
           return item[0];
    })
    .value();

我有两个问题:

  1. list 是一个二维数组(包含 id 和出现次数——见下文),而不仅仅是一个 id 列表。我如何让它只是一个 ID 列表?

    0: "aaYiWFxdtV" 1: 2

  2. 这似乎不是很有效(当我有数百个项目时,我认为这可能不是最好的方法)。我可以用更少的步骤完成吗?

filter函数只是对数组进行过滤,并不改变其中的项。因此,您应该在此处的谓词函数中 return true|false。

过滤后您可以使用map更改结果项。

var list = _.chain(allpeople)
    .countBy(function (regentry) {
        return regentry.get('Student').id;
    })
    .pairs()
    .filter(function (item) {
        return item[1] >= 2;
    })
    .map(function (item) {
        return item[0];
    })
    .value();

关于你的第二个问题:我不知道有任何其他方法可以做到这一点。但我对 underscore.js 也不太熟悉。也许其他人可以在这里回答。

代码可以稍微简化并return你想要的:

var result = _.chain(allpeople)
    .countBy(function(regentry) {
        return regentry.get('Student').id;
    })
    .pick(function(count){
        return count >= 2;
    })
    .keys()
    .value();

然后 countBy function will return an object where the keys are the ids and their values will be their count. Pick 可用于 select 传递谓词的键(其中计数大于或等于 2)。

 var allpeople = [
  { id: 1 },
  { id: 2 },
  { id: 3 },
  { id: 2 },
  { id: 3 }
 ];

 var result = _.chain(allpeople)
     .countBy(function(regentry) {
         return regentry.id;
     })
     .pick(function(count){
      return count >= 2;
     })
     .keys()
     .value();


    document.getElementById('results').textContent = JSON.stringify(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore.js"></script>

<pre id="results"></pre>