1

I have an array of object as follows:

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.

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.

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} ]
6
  • 1
    "with similar keys" what is similar? same? Commented Jul 17, 2020 at 10:50
  • @NikitaMadeev I mentioned it, Need to do this without the reduce method. Commented Jul 17, 2020 at 10:54
  • please add your try. Commented Jul 17, 2020 at 11:01
  • What did you try so far? Commented Jul 17, 2020 at 11:01
  • is it guaranteed to have just one attribute per object ? Commented Jul 17, 2020 at 11:05

2 Answers 2

1

A code without using 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.

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)

Sign up to request clarification or add additional context in comments.

Comments

1

Similar to the answer above, but makes use of a 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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.