操作对象数组

时间:2019-01-22 04:49:30

标签: javascript arrays loops

我有一个对象数组,显示如下:

var dataArray = [{ "moment": "18 January 2019", "val": 53 },
                 { "moment": "18 January 2019", "val": 69 },
                 { "moment": "18 January 2019", "val": 52 },
                 {"moment": "21 January 2019", "val": 52 },
                 { "moment": "21 January 2019", "val": 52 },
                 { "moment": "21 January 2019", "val": 52 }]

我想做的是将元素 moment 的值和当时的 val 的平均值放入新数组中。例如:

result =[{moment: "18 January 2019", "val": 58},
{moment: "21 January 2019", "val": 52}].

目前,我设法将每个日期的一次出现放在新数组结果中,但是由于我不知道如何在两个值之间进行区分,因此我很难用平均值来表示从另一个日期的值中获取一个日期。任何帮助将不胜感激。

和平

6 个答案:

答案 0 :(得分:4)

您可以使用reduce来做到这一点。

在这里,我们首先按时间汇总值,然后还不进行计数。相似的时刻。然后通过它映射并使用合计值和计数找到平均值。

var dataArray = [{ "moment": "18 January 2019","val": 53 },{ "moment": "18 January 2019", "val": 69 },{ "moment": "18 January 2019", "val": 52 },{"moment": "21 January 2019", "val": 52 },                { "moment": "21 January 2019", "val": 52 },                { "moment": "21 January 2019", "val": 52 }]
                 
let output = dataArray.reduce((op,cur)=>{
  if( op[cur.moment] ){
    op[cur.moment].val += cur.val;
    op[cur.moment].count++;
  } else {
    op[cur.moment] = cur
    op[cur.moment].count = 1;
  }
  return op;
},{})

let final = Object.values(output).map(e => {
   return {
    moment: e.moment,
    val: e.val/e.count
   } 
})

console.log(final)

答案 1 :(得分:0)

var totalCount = 0;
var divBy = 0;
var momentToCheck = "21 January 2019"
for(int i= 0; i<dataArray.length; i++) {
    if (dataArray[i].moment === momentToCheck) {
        totalCount+= dataArray[i].val;
        divBy++;
    }
}
var newAvg = totalCount/divBy;
dataArray.push({moment:momentToCheck, val:newAvg});

答案 2 :(得分:0)

首先执行分组,然后对每个组进行平均可能是有意义的。例如:

const dataArray = [{ "moment": "18 January 2019", "val": 53 },
                   { "moment": "18 January 2019", "val": 69 },
                   { "moment": "18 January 2019", "val": 52 },
                   { "moment": "21 January 2019", "val": 52 },
                   { "moment": "21 January 2019", "val": 52 },
                   { "moment": "21 January 2019", "val": 52 }]
                   
const groups = dataArray.reduce((r, { moment, val }) => {
  (r[moment] = r[moment] || []).push(val)  
  return r
}, {})

const avg = arr => arr.reduce((r, x) => r + x, 0) / arr.length

const result = Object.entries(groups).map(([moment, arr]) => ({
  moment,
  avg: avg(arr)
}))

console.log(result)

  

答案 3 :(得分:0)

您可以使用reduce

通过以下方式获得预期的结果
var dataArray = [{
        "moment": "18 January 2019",
        "val": 53
    },
    {
        "moment": "18 January 2019",
        "val": 69
    },
    {
        "moment": "18 January 2019",
        "val": 52
    },
    {
        "moment": "21 January 2019",
        "val": 52
    },
    {
        "moment": "21 January 2019",
        "val": 52
    },
    {
        "moment": "21 January 2019",
        "val": 52
    }
];

const result = dataArray.reduce((accumulator, currentValue, index, array) => {
    if (!accumulator[currentValue.moment]) {
        accumulator[currentValue.moment] = array
            .filter(arr => arr.moment === currentValue.moment)
            .reduce((acc, val, idx, coll) => {
                acc += val.val;

                if (idx === coll.length - 1) {
                    return acc/coll.length;
                } else {
                    return acc;
                }
        }, 0);
    }

    return accumulator;
}, []);

console.log(result); // [ '18 January 2019': 58, '21 January 2019': 52 ]

答案 4 :(得分:0)

使用数组reduce并在回调内检查arument数组的矩值是否相同

var dataArray = [{
    "moment": "18 January 2019",
    "val": 53
  },
  {
    "moment": "18 January 2019",
    "val": 69
  },
  {
    "moment": "18 January 2019",
    "val": 52
  },
  {
    "moment": "21 January 2019",
    "val": 52
  },
  {
    "moment": "21 January 2019",
    "val": 52
  },
  {
    "moment": "21 January 2019",
    "val": 52
  }
]

let avgVal = dataArray.reduce(function(acc, curr) {
  let findIfHasDate = acc.findIndex((item) => {
    return item.moment === curr.moment

  });

  if (findIfHasDate === -1) {
    acc.push({
      moment: curr.moment,
      totalVal: curr.val,
      totalcount: 1

    })
  } else {
    acc[findIfHasDate].totalVal = (acc[findIfHasDate].totalVal + curr.val);
    acc[findIfHasDate].totalcount += 1;
  }

  return acc;
}, []).map((item) => {
  return {
    moment: item.moment,
    avg: (item.totalVal) / item.totalcount
  }
})

console.log(avgVal)

答案 5 :(得分:0)

const sumRow = (sum, count) => ({ sum, count })

const summarize = data => data.reduce((a, c) => (prev => (
  { ...a, [c.moment]: sumRow(prev.sum + c.val, prev.count + 1) }
))(a[c.moment] || sumRow(0, 0)), {})

const average = summary => Object.keys(summary).map(
  k => ({ moment: k, val: (summary[k].sum / summary[k].count) })
)
 
console.log(average(summarize([
  { "moment": "18 January 2019", "val": 53 },
  { "moment": "18 January 2019", "val": 69 },
  { "moment": "18 January 2019", "val": 52 },
  { "moment": "21 January 2019", "val": 52 },
  { "moment": "21 January 2019", "val": 52 },
  { "moment": "21 January 2019", "val": 52 }
])))