James_Inger
James_Inger

Reputation: 93

Group & count objects in array of objects by lat & lng

I have the following array in Jquery, which is plotting a Google Map, what I want to do is group the lat and lng co-ordinates that are the same. SO in the example below the first 4 would be grouped and the last 2 grouped together

Oringinal Array

   var markers = [
{
    "title": 'Duncan-Desktop',
    "lat": '-41.2283',
    "lng": '174.8700',
    "description": 'Duncan-Desktop'
},
{
    "title": 'james-dev',
    "lat": '-41.2283',
    "lng": '174.8700',
    "description": 'james-dev'
},
{
    "title": 'james-laptop',
    "lat": '-41.2283',
    "lng": '174.8700',
    "description": 'james-laptop'
},
{
    "title": 'MX-MIC-1812-3-0000000105',
    "lat": '-41.2283',
    "lng": '174.8700',
    "description": 'MX-MIC-1812-3-0000000105'
},
{
    "title": 'MX-MIC-1812-3-0000000106',
    "lat": '-42.5443',
    "lng": '175.458',
    "description": 'MX-MIC-1812-3-0000000106'
},
{
    "title": 'MX-MIC-1812-3-0000000107',
    "lat": '-42.5443',
    "lng": '175.458',
    "description": 'MX-MIC-1812-3-0000000107'
}

];

I am basically wanting an output of the count for each exact location, the lat and lng, and a string of the titles joined together.

Like this

var markers = [
    {
        "title": 'Duncan-Desktop, james-dev, james-laptop, MX-MIC-1812-3-0000000105',
        "lat": '-41.2283',
        "lng": '174.8700',
        "count": '4'
    },
    {
        "title": 'MX-MIC-1812-3-0000000106, MX-MIC-1812-3-0000000107',
        "lat": '-42.5443',
        "lng": '175.458',
        "count": '2'
    }
];

I've tried a few each loop but can't get my head around it - yet. Any help would be awesome

Upvotes: 0

Views: 95

Answers (1)

Akrion
Akrion

Reputation: 18525

You can do this via Array.reduce in order to group on a key composed of the lat & lng and then get the count/title via incrementing/concatenating each respectively:

const data = [{ "title": 'Duncan-Desktop', "lat": '-41.2283', "lng": '174.8700', "description": 'Duncan-Desktop' }, { "title": 'james-dev', "lat": '-41.2283', "lng": '174.8700', "description": 'james-dev' }, { "title": 'james-laptop', "lat": '-41.2283', "lng": '174.8700', "description": 'james-laptop' }, { "title": 'MX-MIC-1812-3-0000000105', "lat": '-41.2283', "lng": '174.8700', "description": 'MX-MIC-1812-3-0000000105' }, { "title": 'MX-MIC-1812-3-0000000106', "lat": '-42.5443', "lng": '175.458', "description": 'MX-MIC-1812-3-0000000106' }, { "title": 'MX-MIC-1812-3-0000000107', "lat": '-42.5443', "lng": '175.458', "description": 'MX-MIC-1812-3-0000000107' } ]

const result = data.reduce((r,{title, lat, lng, description}) => {
  let key = `${lat}${lng}`
  r[key] = r[key] || { title: '', lat, lng, count: 0 }
  r[key].title = r[key].title.concat(' ', description)
  r[key].count += 1
  return r
}, {})

console.log(Object.values(result))

Upvotes: 1

Related Questions