рассчитать процент вместо суммы - PullRequest
0 голосов
/ 12 июня 2018

На самом деле моя функция вычисляет сумму всех одинаковых ключей в каждом объекте

const arr = [{id:1, "my color":1,"my fruit":4},{id:2,"my color":2,"my fruit":4}];

const res = arr.reduce((a, { id, ...rest }) => {
  Object.entries(rest).forEach(([key, val]) => {
    a[key] = (a[key] || 0) + val;
  });
  return a;
}, {});

result is >> [{"my color":3,"my fruit":8}

Я бы хотел получить их процент (значение / сумму значений), а не их сумму, как это

{ "my color": 27, "my fruit": 73 }

Ответы [ 2 ]

0 голосов
/ 12 июня 2018

Попробуйте следовать

var obj = {"my color":3,"my fruit":8};
var total = Object.values(obj).reduce((a,c) => a+c, 0);
Object.keys(obj).forEach(k => obj[k] = Math.round(obj[k]*100/total));
console.log(obj);
0 голосов
/ 12 июня 2018

Ну, просто сначала суммируйте все значения, а затем разделите каждую запись на:

// Sum up all properties with same key
const sum = { };

for(const entry of array) {
  for(const [key, value] of Object.entries(entry)) {
     sum[key] = (sum[key] || 0) + value;
  }
}

// Map the array to an array of percentages   
const percentage = array.map(entry => {
  const result = {};
  for(const [key, value] of Object.entries(entry)) {
     result[key] = value / sum[key] * 100;
  }
  return result;
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...