Count duplicates within an Array of Objects

Solution 1:

For example:

counter = {}

yourArray.forEach(function(obj) {
    var key = JSON.stringify(obj)
    counter[key] = (counter[key] || 0) + 1
})

Docs: Array.forEach, JSON.stringify.

Solution 2:

Object.prototype.equals = function(o){
    for(var key in o)
        if(o.hasOwnProperty(key) && this.hasOwnProperty(key))
            if(this[key] != o[key])
                return false;
    return true;
}
var array = [/*initial array*/],
    newArray = [],
    ok = true;
for(var i=0,l=array.length-1;i<l;i++)
    for(var j=i;j<l+1;j++)
    {
       if(!array[i].equals(array[j]))
           newArray.push(array[i]);
    }

Solution 3:

We are required to write a JavaScript function that takes in one such array of objects. The function creates and return a new array in which no objects are repeated (by repeated we mean objects having same value for "Country" property.)

Moreover, the function should assign a count property to each object that represents the number of times they appeared in the original array.

const arr = [
   {
      "Country": "BR",
      "New Lv1−Lv2": "#N/A"
   },
   {
      "Country": "BR",
      "New Lv1−Lv2": "#N/A"
   },
   {
      "Country": "",
      "New Lv1−Lv2": "test"
   }];
   const convert = (arr) => {
      const res = {};
      arr.forEach((obj) => {
         const key = `${obj.Country}${obj["New Lv1−Lv2"]}`;
         if (!res[key]) {
            res[key] = { ...obj, count: 0 };
         };
         res[key].count += 1;
      });
   return Object.values(res);
};
console.log(convert(arr));

know more