简体   繁体   中英

Get json objects with max, min and avg javascript

I have some json code that I use with javascript. I need to show the max, min and avg of the scans number but with the json objects.

This is my json example:

{
  'name': 'same',
  'scans': 3674,
  'date': '2003-02-01'
},
{
  'name': 'same',
  'scans': 8347,
  'date': '2005-12-03'
},
{
  'name': 'same',
  'scans': 6876,
  'date': '2014-03-06'
}

The result for max should be:

{
  'name': 'same',
  'scans': 8347,
  'date': '2005-12-03'
}

The result for min should be:

{
  'name': 'same',
  'scans': 3674,
  'date': '2003-02-01'
}

The result for avg should be:

{
  'name': 'same',
  'scans': 6299,
}

with array reduce..

 var myJSON = [ { 'name': 'same', 'scans': 3674, 'date': '2003-02-01' } , { 'name': 'same', 'scans': 8347, 'date': '2005-12-03' } , { 'name': 'same', 'scans': 6876, 'date': '2014-03-06' } ]; var Max_JSO = myJSON.reduce( (acc, cur )=> ((acc.scans > cur.scans)? acc : cur) ); var Min_JSO = myJSON.reduce( (acc, cur )=> ((acc.scans < cur.scans)? acc : cur) ); var Avg_JSO = myJSON.reduce( (acc, cur, idx, arr )=> { let sum = acc.scans + cur.scans, no = idx +1; if (no === arr.length) { sum = sum / no }; return { 'name': cur.name, 'scans': sum } }); console.log ('max =', JSON.stringify(Max_JSO) ); console.log ('min =', JSON.stringify(Min_JSO) ); console.log ('Avg =', JSON.stringify(Avg_JSO) );

Try this:

function maxScans(jsonData) {
  let max = jsonData[0].scans;

  for (let i = 1; i < jsonData.length; i ++) {
    if (jsonData[i].scans > maxScans) maxScans = jsonData[i]
  }
  return {
    name: jsonData[0].name,
    scans: max
  }
}

The complete answer would involve tallying the total scans as you iterate over the data, then using that to calculate the average.

You could write some reducers for example that can handle the task.

const json = [
  {
    name: 'same',
    scans: 3674,
    date: '2003-02-01',
  },
  {
    name: 'same',
    scans: 8347,
    date: '2005-12-03',
  },
  {
    name: 'same',
    scans: 6876,
    date: '2014-03-06',
  },
];

const max = json.reduce((acc, obj) => {
  if (!acc || obj.scans > acc.scans) {
    return obj;
  }

  return acc;
});

const min = json.reduce((acc, obj) => {
  if (!acc || obj.scans < acc.scans) {
    return obj;
  }

  return acc;
});

const avg = json
  .reduce(
    (acc, obj) => {
      return {
        ...acc,
        name: obj.name,
        value: acc.value + obj.scans,
        count: acc.count + 1,
      };
    },
    {
      value: 0,
      name: '',
      count: 0,
      exec() {
        return {
          name: this.name,
          scans: this.value / this.count,
        };
      },
    },
  )
  .exec();

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM