简体   繁体   中英

Calculation on array objects having same property values

I have an array as-

const a = [
  {
    value: 1,
    week: 'week1',
  },
  {
    value: 2,
    week: 'week1',
  },
  {
    value: 3,
    week: 'week16',
  },
  {
    value: 4,
    week: 'week0',
  },
  {
    value: 5,
    week: 'week16',
  },
]

I want to have a modified array in the following way-

let modified = [
  {
    value: 1.5,
    week: 'week1',
  },
  {
    value: 4,
    week: 'week16',
  },
  {
    value: 4,
    week: 'week0',
  },
]

In this modified array, the duplicate week has been put only once and the value has been replaced by average of total value in the particular duplicate objects.

You can collect the values in an object, and then calculate the average by dividing their sum over the number of available values for a given week:

 const a = [{ value: 1, week: 'week1', }, { value: 2, week: 'week1', }, { value: 3, week: 'week16', }, { value: 4, week: 'week0', }, { value: 5, week: 'week16', }]; const result = Object.entries( a.reduce((a, {value, week}) => ({...a, [week]: [...a[week] || [], value] }), {}) ).map(([week, values]) => ({ week, value: values.reduce((a, v) => a + v, 0) / values.length })); console.log(result);

you can do it in simple way like below,

1.Create a map and added values of similar week and kept their count 2.Then created modified from that.

const a = [
    {
        value: 1,
        week: 'week1',
    },
    {
        value: 2,
        week: 'week1',
    },
    {
        value: 3,
        week: 'week16',
    },
    {
        value: 4,
        week: 'week0',
    },
    {
        value: 5,
        week: 'week16',
    },
];


const helperMap = {}

a.forEach((obj) => {
    if (!!helperMap[obj.week]) {
        helperMap[obj.week]['sum'] += obj.value;
        helperMap[obj.week]['count'] += 1;
    } else {
        helperMap[obj.week] = { sum: obj.value, count: 1 };
    }
});

const modified = [];
for (let week in helperMap) {
    let avgValue = helperMap[week]['sum'] / helperMap[week]['count'];
    modified.push({ week, value: avgValue });
}

console.log(modified)

We can do it in short forms using inbuilt functions also, but it will be better to understand the concept

 const a = [ { value: 1, week: 'week1', }, { value: 2, week: 'week1', }, { value: 3, week: 'week16', }, { value: 4, week: 'week0', }, { value: 5, week: 'week16', }, ] let modified = []; a.forEach(item => { let match = modified.find(m => m.week === item.week); if (match) match.value = (match.value + item.value); else modified.push(item); }); modified.forEach(m => m.value = m.value / a.filter(a => a.week === m.week).length); console.log(modified)

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