admin管理员组

文章数量:1296302

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 ?

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 ?

Share edited Oct 17, 2017 at 6:08 Subhajit asked Oct 17, 2017 at 5:57 SubhajitSubhajit 8943 gold badges17 silver badges39 bronze badges 5
  • 3 [india: 7, indonesia: 3, usa: 1] -> Not a valid JS array or object. – Nisarg Shah Commented Oct 17, 2017 at 5:58
  • Why a single loop ? – Titus Commented Oct 17, 2017 at 5:59
  • did you mean [{india: 7}, {indonesia: 3}, {usa: 1}] ? – TGW Commented Oct 17, 2017 at 6:01
  • [india: 7, indonesia: 3, usa: 1] is wrong. is it {india: 7, indonesia: 3, usa: 1}? – Nitheesh Commented Oct 17, 2017 at 6:12
  • The arr variable must be an object and not an array, as in your case if you return the variable after assigning the values you will get []. But if the arr variable was an object you would definitely get {india: 7, indonesia: 3, usa: 1}. Reason being that the in array, arr["india"] "india" means the position which cannot be true. – Karan Singh Dhir Commented Oct 17, 2017 at 6:21
Add a ment  | 

6 Answers 6

Reset to default 8

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);

If your objects is like this var arr = {india: 7, indonesia: 3, usa: 1};, you can do it in this way.

var arr =  {india: 7, indonesia: 3, usa: 1};
var sum = 0;
//Finding the sum
for(key in arr){
    sum += arr[key];
}
console.log("Sum of the object values is = " + sum);
//Finding the average
for(key in arr){
    arr[key] = (arr[key]/sum)*100;
}
console.log(arr);

Loop through each key and reassigned the val like this:

var countries = [];
countries["india"] = 7;
countries["indonesia"] = 3;
countries["usa"] = 1;

for (var country in countries){
    if (countries.hasOwnProperty(country)) {
        countries[country] = (countries[country] / 11 * 100).toFixed(2)
    }
}

console.log(countries)

[india: 7, indonesia: 3, usa: 1]is wrong, you need an object, like {india: 7, indonesia: 3, usa: 1}

So, I think you need an function to do what you need, simple:

var obj =  {india: 7, indonesia: 3, usa: 1}
const getPercent = (obj) {
    let sum = 0

    for (key in obj) {
        sum += obj[key]
    }

    for (key in obj) {
        obj[key] = (obj[key]/sum)*100
    }

    return obj
}

Once you change the obj, you run getPercent(obj), then you get a return, that is what's you need. May helpful.

So, suppose you have a valid array:

var myArray = { 'key1': 2, 'key2': 5, 'key3': 14 };

/* iterates through an associative array, calculates each percentage and 
    adds it to a similar associative array 
    
    The percentages are not rounded
 */
function getPercentagePerKey(myArray) {
  var sum = getSum(myArray);
  var arrayWithPercentages = [];
  for (key in myArray) {
    val = myArray[key];
    percentage = (val / sum) * 100;
    arrayWithPercentages.push({key, percentage});
  }
  return arrayWithPercentages;  
}

/* returns the sum given from an 'associative' array */
function getSum(myArray) {
  var sum = 0;
  for (key in myArray) {
    sum += myArray[key];
  }
  return sum;
}

percentageArray = getPercentagePerKey(myArray);
console.log(percentageArray);

0: {key: "key1", percentage: 9.523809523809524}
1: {key: "key2", percentage: 23.809523809523807}
2: {key: "key3", percentage: 66.66666666666666}

You can make getters from object properties if it is allowed:

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

var sum = 0;
var percent = function(n){
  return function(){ return n/sum*100; }
}

for (var k in arr) {
  sum+=arr[k];
  arr[k]=percent(arr[k]);
}

console.log(arr.india());
console.log(arr.usa());
console.log(arr.indonesia());

本文标签: javascriptCalculate percentage from associative array in JSStack Overflow