0

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 structure

4
  • Use array's .reduce function (w3schools.com/jsref/jsref_reduce.asp) Commented Mar 11, 2020 at 21:57
  • @curiousdev reduce would work here. However the data is nested so it's a little trickier. Commented Mar 11, 2020 at 22:00
  • @JosephCho it works under presumption that environment['4*'] is always present Commented Mar 11, 2020 at 22:16
  • And also assuming environment['4*] is valid. Yep that's correct Commented Mar 11, 2020 at 22:19

2 Answers 2

2

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)
}
Sign up to request clarification or add additional context in comments.

3 Comments

The division by the array's length is in the wrong place; it should be outside the reduce: d.values.reduce((avg, item) => avg + item, 0) / d.values.length;
The division is in correct place. Your way was (a+b)/2. My way was a/2 + b/2.
Ah I see my mistake now: I had run reduce((avg, item, _, arr) => avg + item / arr.length) (note no , 0 at the end), which returns an incorrect value; theory-wise, I did think yours was also correct, but was surprised when I (incorrectly) tested it.
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;
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.