I currently have this function
function radius(d) {
return d.values[0].environment["4*"];
console.log(d);
}
However id liked to be able to average all of the 4* environment values for each document(there are 6 in the example below) and return this as the radius. Im new to JS so no idea how to do this. can you help. here is the structure of the data
You can use reduce function:
function radius(d) {
return d.values.reduce(function(avg, item, index, array) {
return avg + item.environtment['4*'] /array.length
},0)
}
It's tough to answer the question accurately without testing the whole data structure. Based on what you've provided this should work:
function radius(d) {
let sum = 0;
for (let i=0; i<d.length; i++) {
let num = parseInt(d[i].environment['4*']);
if (!isNaN(num)) sum += num;
}
return sum;
}
We loop through the array, and if environment['4*']
is a valid number we sum it up. Functionally it would be:
function radius(d) {
const filtered = d.values.filter((x) => {
let num = parseInt(x.environment['4*']);
return !isNaN(num);
});
const sum = filtered.reduce((acc, val) => {
return acc+val;
},0)
return sum/filtered.length;
}
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.