I have a for loop that goes through a series of data. I would like to store the result of elevations[i].elevation*3.28084; in an array. Right now it only has one value outside of the loop.
var data2 = [];
for (var i = 0; i < elevations.length; i++) {
data2 = elevations[i].elevation*3.28084; // convert meters to feet
}
I have a for loop that goes through a series of data. I would like to store the result of elevations[i].elevation*3.28084; in an array. Right now it only has one value outside of the loop.
var data2 = [];
for (var i = 0; i < elevations.length; i++) {
data2 = elevations[i].elevation*3.28084; // convert meters to feet
}
Share
Improve this question
asked Mar 28, 2018 at 16:48
blg2blg2
38510 silver badges23 bronze badges
4 Answers
Reset to default 3You need to assign to array entries, not to the array itself:
data2[i] = elevations[i].elevation*3.28084;
// --^^^
Alternately, use push
:
data2.push(elevations[i].elevation*3.28084);
// --^^^^^^-------------------------------^
You want to push new items elevation[i].elevation * 3.28084
into array. However, it's more convenient to use Array.prototype.map:
var data2 = elevations.map(function (elevation) {
return elevation.elevation * 3.28084
})
You're only assigning a value to the previously declared variable data2
, use the function push
instead to add new values to the array, or use the current index to add new values to that array.
var data2 = [];
for (var i = 0; i < elevations.length; i++) {
data2.push(elevations[i].elevation * 3.28084); // convert meters to feet
}
You have to push your result to that array like this :
var data2 = [];
for (var i = 0; i < elevations.length; i++) {
data2.push(elevations[i].elevation*3.28084); // convert meters to feet
}
Or you can insert data to that array using map :
var data2 = elevations.map(function(value){
return value.elevation*3.28084;
}