对计算结果感到困惑

时间:2020-03-23 12:23:32

标签: javascript json

我有一个json,如下所示。

const words = [{
    "Id": "1",
    "Status": "Not Started"
  },
  {
    "Id": "2",
    "Status": "Not Started"
  },
  {
    "Id": "3",
    "Status": "Completed"
  },
  {
    "Id": "4",
    "Status": "Not Started"
  },
  {
    "Id": "5",
    "Status": "Not Started"
  }];

我要使用Javascript计算Completed的百分比,在当前的json中,该百分比应该为20%,因为有5项并且其中1个是完整的。

这是我编写的代码。

const users = [
  {
    "Id": "1",
    "Status__c": "Not Started"
  },
  {
    "Id": "2",
    "Status__c": "Not Started"
  },
  {
    "Id": "3",
    "Status__c": "Completed"
  },
  {
    "Id": "4",
    "Status__c": "Not Started"
  },
  {
    "Id": "5",
    "Status__c": "Not Started"
  }
];

let nS = users.filter(it => it.Status__c==='Not Started');
let cm = users.filter(it => it.Status__c!=='Not Started');

console.log(nS.length +' \t' +cm.length);

这给出了计数的确切结果。但是在这里我要百分比。结果中可能也有3或7(并非始终有5个),我希望该百分比甚至在这些情况下也能显示结果。

谢谢

4 个答案:

答案 0 :(得分:4)

只需使用reduce计算完成的项目,然后将其除以项目总数即可:

let completedCount = users.reduce((count, it) => count + (it.Status__c === "Completed" ? 1 : 0), 0);

let completedPercentage = 100 * completedCount / users.length;

注意:您可能要在除法之前检查users.length !== 0是否

答案 1 :(得分:2)

按状态过滤,然后进行百分比数学计算。

const users = [{ "Id": "1", "Status__c": "Not Started" }, { "Id": "2", "Status__c": "Not Started" }, { "Id": "3", "Status__c": "Completed" }, { "Id": "4", "Status__c": "Not Started" }, { "Id": "5", "Status__c": "Not Started" }];

const percentComplete = (data) => 
    (data.filter(({Status__c: s}) => 
        s === 'Completed').length / data.length) * 100

const result = percentComplete(users)
console.log(`${result.toFixed()}%`)

答案 2 :(得分:0)

使用基本的简化循环。

const words = [{
    "Id": "1",
    "Status": "Not Started"
  },
  {
    "Id": "2",
    "Status": "Not Started"
  },
  {
    "Id": "3",
    "Status": "Completed"
  },
  {
    "Id": "4",
    "Status": "Not Started"
  },
  {
    "Id": "5",
    "Status": "Not Started"
  }
];

function calculatePercentageByStatus(status, arr) {
  let total = arr.length;
  let matched = 0;
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].Status === status) {
      matched++;
    }
  }

  return (matched / total) * 100;

}

console.log("percentage of Completed " + calculatePercentageByStatus("Completed", words) + "%");

console.log("percentage of Not Started " + calculatePercentageByStatus("Not Started", words) + "%");

答案 3 :(得分:0)

我觉得这很简单。

console.log(cm.length * 100 / users.length + '%');

这应该有效。