showtime
showtime

Reputation: 1462

How can I find the highest occurrence of an item in an array of objects?

I have an array of objects and I would like to find the highest occurrence of an item in each object and return the frequency:

var arr = [{spot_id: 6, spot_no: 6, gate_id: 6}, {spot_id: 16, spot_no: 17, gate_id: 5}, {spot_id: 5, spot_no: 5, gate_id: 5}, {spot_id: 11, spot_no: 11, gate_id: 5}, {spot_id: 15, spot_no: 16, gate_id: 4}, {spot_id: 4, spot_no: 4, gate_id: 4}, {spot_id: 10, spot_no: 10, gate_id: 4}, {spot_id: 14, spot_no: 15, gate_id: 3}, {spot_id: 9, spot_no: 9, gate_id: 3}, {spot_id: 3, spot_no: 3, gate_id: 3}, {spot_id: 8, spot_no: 8, gate_id: 2}, {spot_id: 13, spot_no: 14, gate_id: 2}, {spot_id: 2, spot_no: 2, gate_id: 2}, {spot_id: 7, spot_no: 7, gate_id: 1}, {spot_id: 12, spot_no: 13, gate_id: 1}];

I have tried to find using this code but it returns an object with values 1, 1, 1 for each field:

var items = arr.sort((a, b) =>
  arr.filter(v => v.gate_id === a.gate_id).length -
  arr.filter(v => v.gate_id === b.gate_id).length
).pop();

I want it to return the highest occurrence of gate_id which in this array is either 5,5,5 or 4,4,4 or 3,3,3 or 2,2,2, basically just one of them, i dont care which one and I want to return the frequency , in this case the frequency is 3 times.

Upvotes: 0

Views: 796

Answers (2)

Nikil Munireddy
Nikil Munireddy

Reputation: 328

This code will return the maximum occurrence of a particular value. In this example it is 3. I have kept the code simple hope this helps

var arr  = [{spot_id: 6, spot_no: 6, gate_id: 6}, {spot_id: 16, spot_no: 17, gate_id: 5}, {spot_id: 5, spot_no: 5, gate_id: 5}, {spot_id: 11, spot_no: 11, gate_id: 5}, {spot_id: 15, spot_no: 16, gate_id: 4}, {spot_id: 4, spot_no: 4, gate_id: 4}, {spot_id: 10, spot_no: 10, gate_id: 4}, {spot_id: 14, spot_no: 15, gate_id: 3}, {spot_id: 9, spot_no: 9, gate_id: 3}, {spot_id: 3, spot_no: 3, gate_id: 3}, {spot_id: 8, spot_no: 8, gate_id: 2}, {spot_id: 13, spot_no: 14, gate_id: 2}, {spot_id: 2, spot_no: 2, gate_id: 2}, {spot_id: 7, spot_no: 7, gate_id: 1}, {spot_id: 12, spot_no: 13, gate_id: 1}];
gate_id_counter={}
maximum=0

arr.map(ele => {
  // Create a frequency map of each value and their count { '1': 2, '2': 3, '3': 3, '4': 3, '5': 3, '6': 1 }
  // Choosing the maximum from the frequency map
  if( ele.gate_id in gate_id_counter){
    gate_id_counter[ele.gate_id]+=1
    if( gate_id_counter[ele.gate_id]>= maximum){
      maximum=gate_id_counter[ele.gate_id]
    }
  }
  else{
    gate_id_counter[ele.gate_id]=1
  }
})
console.log("Maximum count is "+ maximum)

Upvotes: 0

showtime
showtime

Reputation: 1462

found the solution.

below I find the occurrences of all values (gate_id):

var result = array.reduce( (acc, o) => (acc[o.gate_id] = (acc[o.gate_id] || 0)+1, acc), {} );

and here I found the highest value of all the occurences:

const max = Math.max.apply(null, Object.values(result));

Upvotes: 1

Related Questions