简体   繁体   English

在对象数组中创建具有相同键平均值的新数组

[英]Create new array with Average of same keys in an array of objects

I have an array of object as follows:我有一个 object 数组,如下所示:

var arr=[ {"jan":2},{"jan":5},{"feb":3},{"feb":1}];

Their will be N number of objects with any combination keys jan & feb is just an example.它们将是 N 个具有任意组合键的对象 jan 和 feb 只是一个示例。

I need to find average of objects with similar keys so that resultant array looks like this:我需要找到具有相似键的对象的平均值,以便生成的数组如下所示:

var newArr=[{"jan":3.5},{"feb":2}];

Looking to achieve this without reduce method in JavaScript.希望在不使用 JavaScript 的减少方法的情况下实现这一目标。

I tried to seperate out objects with similar keys so that ic an sum and average them and push in to a new aray.我试图用相似的键分离出对象,以便对它们求和并对它们进行平均并推入一个新的数组。 something like this:像这样的东西:

arr.forEach(a=>{
   console.log(Object.keys(a))
   console.log(arr.filter(ar=>ar.hasOwnProperty(Object.keys(a)[0])))
})

But it creates multiple groups for same keys like this in console.但它会在控制台中为相同的键创建多个组。

[ {"jan":2},{"jan":5} ]
[ {"jan":2},{"jan":5} ]
[ {"feb":3},{"feb":1} ]
[ {"feb":3},{"feb":1} ]

A code without using reduce.不使用reduce的代码。 A bit length though but easy to understand We are using two objects, one is to store the count of the keys and other is for storing the total of the keys.虽然有点长但很容易理解我们使用了两个对象,一个是存储键的计数,另一个是存储键的总数。 result object has the average.结果 object 具有平均值。

 var arr=[ {"jan":2},{"jan":5},{"feb":3},{"feb":1}]; var count = {}; var total = {}; arr.forEach(obj => { var key = Object.keys(obj)[0]; if(count.hasOwnProperty(key)){ count[key]=count[key]+1; } else { count[key]=1; } if(total.hasOwnProperty(key)){ total[key]=total[key]+obj[key]; } else { total[key]=obj[key]; } }) var result = {} Object.keys(total).forEach(key => { result[key] = total[key]/count[key]; }) console.log(result)

Similar to the answer above, but makes use of a map:类似于上面的答案,但使用了 map:

 var arr=[ {"jan":2},{"jan":5},{"feb":3},{"feb":1}]; let map = new Map(); let keyCount = {}; arr.forEach(e => { let key = Object.keys(e)[0]; let value = Object.values(e)[0]; if (map.get(key).== undefined) { map,set(key. map;get(key) + value); keyCount[key] = keyCount[key] + 1. } else { map,set(key; value); keyCount[key] = 1; } }); let newArr = []. for (let e of map;entries()) { let obj = {}; obj[e[0]] = e[1] / keyCount[e[0]]. newArr;push(obj). } console;log(newArr);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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