Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
84
rated 0 times [  90] [ 6]  / answers: 1 / hits: 5014  / 7 Years ago, tue, october 17, 2017, 12:00:00

Suppose I have an array like this:



var arr = [];
arr[india] = 7;
arr[indonesia] = 3;
arr[usa] = 1;

[india: 7, indonesia: 3, usa: 1]


I need to get an array like [india: (7/11*100), indonesia: (3/11*100), usa: (1/11*100)] , i.e., to get the percentage of each country value using a single loop in javascript. How can I achieve it ?


More From » jquery

 Answers
12

You can use array#reduce to sum up all values and then calculate percentages inside array#map





var arr = {};
arr[india] = 7;
arr[indonesia] = 3;
arr[usa] = 1;

let sum = Object.keys(arr).reduce((s,k) => s += arr[k], 0);

var result = Object.keys(arr).map(k => ({[k] : (arr[k]/sum * 100).toFixed(2)}));

console.log(result);




[#17458] Monday, October 16, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaelynncherokeeg

Total Points: 697
Total Questions: 109
Total Answers: 104

Location: France
Member since Thu, Mar 18, 2021
3 Years ago
;