получить процент от массива объектов, используя angular 6 - PullRequest
0 голосов
/ 28 января 2020

Я хочу получить процент от конкретного объекта, например: У меня есть массив опций: -

options: Array(2)
0: {id: 1, choice: "Yes", answer_count: 1}
1: {id: 2, choice: "No", answer_count: 0}

или массив mcq: -

options: Array(4)
0: {id: 1, choice: "Yes, of course", answer_count: 0}
1: {id: 2, choice: "There is not an immediate need in the product, I a…d it to get a basic understanding of the subject.", answer_count: 1}
2: {id: 3, choice: "This will help me to pursue my learning goal.", answer_count: 0}
3: {id: 4, choice: "No,  I am not sure if it was helpful enough", answer_count: 0}

Мне нужно получить процент choice key от общего числа answer_count key, например: процент choice: "Yes, ofcourse" от answer count of choice: "Yes, ofcourse" to the total of all answer count in options

Может ли кто-нибудь помочь мне найти решение этой проблемы

1 Ответ

1 голос
/ 28 января 2020

Вы можете получить массив свойства answer_count с помощью:

choices.map(function(item) {
    return item['answer_count']
})

Затем вы можете уменьшить этот массив, чтобы получить количество ответов, например:

choices.map(function(item) {return item['answer_count']}).reduce(function (a, b) { 
    return (a + b)
});

Наконец, просто получить процент, разделив answer_count на сумму и умножив результат на 100:

(item['answer_count'] / totalAnswers) * 100

Используя предоставленные вами данные:

let choices = [
  {id: 1, choice: "Yes, of course", answer_count: 0},
  {id: 2, choice: "There is not an immediate need in the product, I a…d it to get a basic understanding of the subject.", answer_count: 1},
  {id: 3, choice: "This will help me to pursue my learning goal.", answer_count: 0},
  {id: 4, choice: "No,  I am not sure if it was helpful enough", answer_count: 0}
];

let totalAnswers = choices.map(function(item) {return item['answer_count']}).reduce(function (a, b) { 
  return (a + b)
});

let percentages = choices.map(function (item) {
  return {
    'id': item['id'],
    'choice': item['choice'], 
    'percentage': (item['answer_count'] / totalAnswers) * 100
  }
})

console.log(percentages);
...