1

I have an object with these properties :

{
    title: 'Test',
    places: [
      {
        id: 1,
        longitude: 48.8469511,
        latitute: 2.3077989,
        address: 'Pont de Bir-Hakeim',
        city: {name: 'Paris', id: 1}
      },
      {
        id: 2,
        longitude: 48.855225,
        latitute: 2.288048,
        address: 'Palais-Musée Galliera, 10 avenue Pierre-1er-de-Serbie',
        city: {name: 'Paris', id: 1}
      },
      {
        id: 3,
        longitude: 50.8283315,
        latitute: -115.2608429,
        address: 'Fortress Moutain',
        city: {name: 'Calgary', id: 2}
      }
    ]
}

Here is the result I want :

[
  {
    id: 1,
    name: 'Paris'
  },
  {
    id: 2,
    name: 'Calgary'
  },
]

How can I achieve that by using groupBy map reduce ? Here is what I tried :

   return from(movie.places).pipe(
      groupBy(place => place.city.name),
      mergeMap(place => place.pipe(map(obj => obj.city.name))),
      toArray()
   );

Which produce :

['Paris', 'Paris', 'Calgary']

It's not very clear in my head on how to use groupBy, map, mergeMap, toArray together... Thanks for the help!

Jérémy Halin
  • 553
  • 4
  • 29

2 Answers2

1

you can do something like this :

source$.pipe(
  map(state => state.places), // transform your source object to list of places.
  // Transform your list of place by list of city, then reduce it for unduplicate it.
  map(state => state.map(e => e.city).reduce( ( acc, cur ) => [
    ...acc.filter( ( obj ) => obj.id !== cur.id ), cur
  ], [] ))
).subscribe(console.log);

i have split in two different map to keep clear my code, you can easily merge it to single map if you prefer.

this code is also not safe for very large collection of data, prefer normalizr approch if you want to efficiently deal with larg data.

live code

source for uniq array of object base from id

Yanis-git
  • 7,737
  • 3
  • 24
  • 41
  • Thanks it's working. About large collection of data, considering I will get data thanks to an API, what should I do ? Returning whole object (so large data) and process it with angular framework or get less data by API but make multiple calls and logic on API's server ? – Jérémy Halin Dec 24 '18 at 11:16
0

In one line, I think, and just using toArray, map, distinct operators you can do:

return from(movie.places).pipe(map(place => place.city), distinct(entry => entry.id),toArray());

Demo

SeleM
  • 9,310
  • 5
  • 32
  • 51