JavaScript Calculate percentage from associative array in JS calculate percentage from 2 numbers,calculate percentage from two numbers,

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 ?

Answer:1

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);
Answer:2

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);
Answer:3

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)
Answer:4

[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.

Answer:5

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);
Answer:6

I just want to ask for an appropriate way to append new elements in jQuery. In the past, I tend to do string concatenation and then append to a div. However, sometimes my data contains special chars (...

I just want to ask for an appropriate way to append new elements in jQuery. In the past, I tend to do string concatenation and then append to a div. However, sometimes my data contains special chars (...

Given the following example: setTimeout(function name(){console.log(1)}, 1000) (callback) Is name() (the callback) considered a function declaration or a named function expression? I know that ...

Given the following example: setTimeout(function name(){console.log(1)}, 1000) (callback) Is name() (the callback) considered a function declaration or a named function expression? I know that ...

I have a Backbone.Marionette item view. It renders a list of items. I want to listen for the scoll event everytime somebody scrolls the list. I assumed this would work: events: { 'scroll ul': '...

I have a Backbone.Marionette item view. It renders a list of items. I want to listen for the scoll event everytime somebody scrolls the list. I assumed this would work: events: { 'scroll ul': '...

  1. capture scroll event javascript
  2. capture scroll event angular
  3. capture scroll event
  4. capture scroll event jquery
  5. capture scroll event angular 4
  6. capture scroll event js
  7. capture scroll event angularjs
  8. capture scroll event div
  9. react capture scroll event
  10. iframe capture scroll event
  11. capture mouse scroll event
  12. capture window scroll event
  13. extjs capture scroll event
  14. excel vba capture scroll event

I would like to use a javascript loop to create multiple HTML wrapper elements and insert JSON response API data into some of the elements (image, title, url, etc...). Is this something I need to go ...

I would like to use a javascript loop to create multiple HTML wrapper elements and insert JSON response API data into some of the elements (image, title, url, etc...). Is this something I need to go ...

  1. javascript using loop
  2. in javascript loop
  3. javascript in loop array
  4. javascript using while loop
  5. create array using loop javascript