Choy
Choy

Reputation: 2117

Building an array out of values from another array

This is a follow up from a question of mine that was just answered concerning parsing numbers in an array.

I have an array, data[], with numbers that I'd like to use in a calculation and then put the resulting values into another array.

So say data[0] = 100. I'd like to find a percentage using the calculatin, (data[0]/dataSum*100).toFixed(2) where dataSum is the sum of all the numbers in data[].

I've tried:

dataPercentage = [];

for (var i=0; i < data.length; i++) {
    data[i] = parseFloat(data[i]);
    dataSum += data[i];

    // looping through data[i] and setting it equal to dataPercentage.
    dataPercentage[] = (data[i]/dataSum*100).toFixed(2);

    // thought maybe I was overriding dataPercentage everytime I looped? 
    dataPercentage[] += (data[i]/dataSum*100).toFixed(2); 
}

I also tried just setting dataPercentage = [(data/dataSum*100).toFixed(2)], but I think this creates a nested array, which I don't think is what I need.

Upvotes: 0

Views: 609

Answers (2)

Felix Kling
Felix Kling

Reputation: 816364

You have to calculate the sum of all values in data before you calculate the percentage. In your code you always use the sum up to the ith item of the data array.

var dataSum = 0.0;
var dataPercentage = [];

for (var i=0; i < data.length; i++) {
    data[i] = parseFloat(data[i]);
    dataSum += data[i];
}

for (var i=0; i < data.length; i++) {
    dataPercentage[i] = (data[i]/dataSum*100).toFixed(2); 
}

I don't know what you try to achieve with your second dataPercentage[] line.

Upvotes: 2

Alex Wayne
Alex Wayne

Reputation: 187014

dataPercentage.push((data[i]/dataSum*100).toFixed(2))

Upvotes: 0

Related Questions