I have an array, pictured below, which contains a number of values which I would like to do some calculations on a then push to a separate array.
This is is an example of the array and data I an working with:
I would like to push this data into an array called formatted, This array must contain the following information:
name - taken from the name form the original array
min - the lowest value from the original array
max - the largest value from the original array
Q1 - this is the lower quartile which is calculated from the original array by adding the p30 and p40 values and dividing by 2
Q4 - this is is the upper quartile value which is calculated by adding the p70 and p80 values together and dividing by 2
median - this is calculated by adding the p50 and p60 values together and dividing by 2
This is an example of how I tried to solve this but as seen below I had a error on every value:
var formated = [];
for(var i=0; i < final.length; i++) {
formated.push({
name: final[i].name,
min: final[i][0],
max: final[i].length -1,
Q1: (final[1] + final[2] / 2),
Q2: (final[5] + final[6] / 2),
meidan: (final[3] + final[4] / 2)
});
}
3 Answers 3
Assuming all of the objects always have the same p-values, this is what you'd need:
var formated = [];
for(var i=0; i < final.length; i++) {
formated.push({
name: final[i].name,
min: final[i].p20,
max: final[i].p90,
Q1: ((final[i].p30 + final[i].p40) / 2),
Q2: ((final[i].p70 + final[i].p80) / 2),
median: ((final[i].p50 + final[i].p60) / 2)
});
}
A more elegant version of the above, using Array.prototype.map():
var formated = final.map(function(item){
return {
name: item.name,
min: item.p20,
max: item.p90,
Q1: ((item.p30 + item.p40) / 2),
Q2: ((item.p70 + item.p80) / 2),
median: ((item.p50 + item.p60) / 2)
};
});
6 Comments
map(). Thanks for pointing it out, though.map(). That's definitely the method I prefer over the for loop.min from final[0] and was trying to pull max from the last key in each object in his original code, from his explanation of how to calculate Q1, Q2 and median, and from his data, which appears to be some sort of statistical dataset.You have objects with different namings.
What you call
final[i][0]
Should be something like
final[i].p20
or similar.
Same for all other references, infact in final[i] doesn't exists a property 0. So final[i][0] is undefined.
Comments
You can use map function for this. Map return a new Array :
const array = [
{name : "0006", p20 : 13367.8, p30: 15654.2, p40 : 17199.8, p50 : 18715, p60 : 20285.4, p70 : 22654.6, p80 : 24910.2, p90 : 30394.2}
];
var formated = array.map(el=>({
name: el.name,
min: el.p20,
max: el.p90,
Q1: ((el.p30 + el.p40) / 2),
Q2: ((el.p70 + el.p80) / 2),
median: ((el.p50 + el.p60) / 2)
}));
console.log(formated);