Gangrel
Gangrel

Reputation: 481

Getting average of object within an array

I'm trying to get an average of the 'min' column within this dataset:

var data = [{
    name: "Site A",
    max: 202,
    min: 0,
    var: 202,
    x: 1,
    product: "Diesel",
    case: "Base Case"
  },
  {
    name: "Site B",
    max: 145,
    min: 147,
    var: -2,
    x: 0,
    product: "Diesel",
    case: "Base Case"
  },
  {
    name: "Site C",
    max: 221,
    min: 238,
    var: -17,
    x: 0,
    product: "Diesel",
    case: "Base Case"
  }]

Can you please advise how I can do this?>

Upvotes: 0

Views: 632

Answers (1)

altocumulus
altocumulus

Reputation: 21578

You can use d3.mean() which takes an accessor function as the second argument. That accessor function will be presented each object in your array and is used to extract the .min property from it.

const average = d3.mean(data, d => d.min);

Have a look at this working demo:

var data = [{
    name: "Site A",
    max: 202,
    min: 0,
    var: 202,
    x: 1,
    product: "Diesel",
    case: "Base Case"
  },
  {
    name: "Site B",
    max: 145,
    min: 147,
    var: -2,
    x: 0,
    product: "Diesel",
    case: "Base Case"
  },
  {
    name: "Site C",
    max: 221,
    min: 238,
    var: -17,
    x: 0,
    product: "Diesel",
    case: "Base Case"
  }];
  
const average = d3.mean(data, d => d.min);

console.log(average);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

Upvotes: 2

Related Questions