Home > Mobile >  Transform list of occurences into map
Transform list of occurences into map

Time:09-14

I have the following interface for a coordinate:

interface Coordinate {
  lat: number;
  lng: number;
}

I will also have an array of such coordinates, example:

0:{lat: 51.95, lng: 20.42}
1:{lat: 51.95, lng: 20.42}
2:{lat: 52, lng: 20.45}
3:{lat: 52, lng: 20.45}

My question is,

How can i transform a list with occurences into a map such that:

Map<Coordinate, number> with Coordinate being the coordinate (no duplicates) and the number being how many times such coordinate occured in the list?

CodePudding user response:

I think it's a lot simpler to transform the coordinates to a string as a key and back:

const map = new Map<Coordinate, number>([...data.reduce((map, coord) => {
    return map.set(coordToKey(coord), (map.get(coordToKey(coord)) ?? 0)   1);
}, new Map<string, number>()).entries()].map(([key, value]) => [keyToCoord(key), value]));

This is because when using objects as keys in maps, it is by reference, so the "same" objects won't map to the same values. Here you can see that it won't work by default; you'll have to add logic to check if the coordinate already exists, which is very inefficient.

As for the keys, here I have chosen to use a comma to separate the values:

const coordToKey = (coord: Coordinate) => `${coord.lat},${coord.lng}`;
const keyToCoord = (key: string) => {
    const [lat, lng] = key.split(",").map(Number);

    return { lat, lng };
};

Playground

  • Related