首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在中获取每个员工10%的数据行的Java脚本

在中获取每个员工10%的数据行的Java脚本
EN

Stack Overflow用户
提问于 2021-06-28 15:36:10
回答 1查看 70关注 0票数 0

你如何获得一个随机抽样的10%的总条目的每个独特的员工?

这将用于获得用于审核的随机样本。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-06-28 17:41:17

所以,如果我理解正确的话,你会想得到每名雇员10%的条目作为随机抽样进行审计。那么,在您的情况下,下面的方法应该是好的。

代码:

代码语言:javascript
复制
function getTenPercent() {
  var sheet = SpreadsheetApp.getActiveSheet();
  // range (including header)
  var range = sheet.getRange("A1:C31");
  // get values of the range
  var values = range.getValues();
  // separate header
  var headers = values.shift();
  // variable to modify where your employee name is stored. 0-indexing
  var nameColumn = 0;
  // get unique names (excluding blank cells)
  var uniqueNames = values.map(row => row[nameColumn]).filter((item, i, ar) => ar.indexOf(item) === i).filter(String);
  // in the data we are going to return, already include the header as the first row
  var data = [headers];

  // for each unique name, we process per name
  uniqueNames.forEach(function (name) {
    // filter our whole data range containing only the current name
    var nameEntries = values.filter(row => row[nameColumn] == name);
    // get its length and get the 10% of it 
    // (using floor so if there are 19 rows, 10% is 1 row)
    var entries = nameEntries.length;
    var tenth = Math.floor(entries / 10);
    // until we get the 10%, loop to get a random row matching the unique name
    for(i=0; i<tenth; i++) {
      var random = Math.floor(Math.random() * nameEntries.length);
      data.push(nameEntries[random]);
      // remove the already picked item from the current list to avoid duplicates
      nameEntries.splice(random, 1);
    }
  });
  // return data
  return data;
}

样本输出:

注意:

  • 您需要根据您的数据
  • 来调整范围,您需要调整名称存储的位置。在我的示例中,我使用0作为nameColumn,因为员工名称在我的第一列中。如果您的列在另一列中,请更改它。
  • 注意到这是0-indexing。因此,如果您的列位于第二列,只需减去1并将其存储在变量nameColumn中。如果您的员工姓名在第二栏:
    • var nameColumn = 1;

,它应该是这样的。

  • 数据不需要像样例那样排序。
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68166182

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档