-2

Given data like

var data = [
    {
        "a" : "x"
        ... (other properties)
    },
    {
        "a" : "x"
        ... (other properties)
    },
    {
        "a" : "y"
        ... (other properties)
    },
]

The count of the most common "a"-property value would be 2, (for "x").

Now, what would be the cleanest way to get this from data?

I assume there might be a nice way to generate an array of the different counts, i.e. [ 2 , 1 ] in this case, and then run Math.max(...array) on this?

But I can't seem to find a clean way of doing this?

MrJalapeno
  • 1,532
  • 3
  • 18
  • 37

1 Answers1

2

var data = [{
    a: "x"
  },
  {
    a: "x"
  },
  {
    a: "y"
  },
]

var countPropertyValues = {};
data.forEach(function(obj) {
  if (countPropertyValues.hasOwnProperty(obj.a)) {
    countPropertyValues[obj.a]++;
  } else {
    countPropertyValues[obj.a] = 1;
  }
});

console.log(countPropertyValues);

var maxPropertyOccurence=0;
var maxPropertyValue;

for(var property in countPropertyValues){

    if(countPropertyValues[property]>maxPropertyOccurence){
      maxPropertyOccurence=countPropertyValues[property];
      maxPropertyValue=property;
    }
}

console.log(maxPropertyOccurence);
console.log(maxPropertyValue);
d4rty
  • 3,970
  • 5
  • 34
  • 73