简体   繁体   中英

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.

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 i th 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM