亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

對計算結果感到困惑

對計算結果感到困惑

慕的地8271018 2022-05-26 16:35:42
我有一個如下的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 個),我希望這個百分比甚至在這些情況下也能顯示結果。
查看完整描述

3 回答

?
桃花長相依

TA貢獻1860條經驗 獲得超8個贊

只需計算已完成的項目reduce,然后將其除以項目總數:


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


let completedPercentage = 100 * completedCount / users.length;

注意:您可能需要users.length !== 0在劃分之前檢查是否。


查看完整回答
反對 回復 2022-05-26
?
HUWWW

TA貢獻1874條經驗 獲得超12個贊

按狀態過濾,然后進行百分比數學。


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()}%`)


查看完整回答
反對 回復 2022-05-26
?
犯罪嫌疑人X

TA貢獻2080條經驗 獲得超4個贊

使用基本的簡化循環。


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) + "%");



查看完整回答
反對 回復 2022-05-26
  • 3 回答
  • 0 關注
  • 177 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號