Computer >> Computer tutorials >  >> Programming >> Javascript

Merge duplicate and increase count for each object in array in JavaScript


Suppose, we have an array of objects like this −

const arr = [
   {code: "AA", gender:"male", DOB:"2000-05-15"},
   {code: "AA", gender:"female", DOB:"2015-05-15"},
   {code:"A0", gender:"female", DOB:"2005-01-01"},
   {code: "A1", gender:"male", DOB:"2015-01-15"}
];

We are required to write a JavaScript function that takes in one such array of objects. The function should count the number of duplicate objects in the array (based on the "code" property of objects) and assign a new count property to each unique object.

The function should also assign a child property to each unique object whose value will be 1 if the age (calculated using "DOB" and current date) is less than 18 years, 0 otherwise.

Example

The code for this will be −

const arr = [
   {code: "AA", gender:"male", DOB:"2000−05−15"},
   {code: "AA", gender:"female", DOB:"2015−05−15"},
   {code:"A0", gender:"female", DOB:"2005−01−01"},
   {code: "A1", gender:"male", DOB:"2015−01−15"}
];
const groupAndAdd = (arr = []) => {
   const result = new Map();
   let nowYear = new Date().getYear();
   arr.forEach(el => {
      let item = result.get(el.code) || {code: el.code, count: 0, female: 0, child: 0 };
      item.count++;
      item.female += el.gender === "female";
      item.child += nowYear − new Date(Date.parse(el.DOB)).getYear() <18;
      result.set(item.code, item);
   });
   return result;
};
console.log(groupAndAdd(arr));

Output

And the output in the console will be −

Map {
   'AA' => { code: 'AA', count: 2, female: 1, child: 1 },
   'A0' => { code: 'A0', count: 1, female: 1, child: 1 },
   'A1' => { code: 'A1', count: 1, female: 0, child: 1 }
}