Building an array out of values from another array
Posted
by George
on Stack Overflow
See other posts from Stack Overflow
or by George
Published on 2010-04-05T20:55:09Z
Indexed on
2010/04/05
21:03 UTC
Read the original article
Hit count: 203
JavaScript
|arrays
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.
© Stack Overflow or respective owner