0

I have array like this one below. How can I group this array by lat and lng?

[{
  name: "a",
  address: {
    lat: 5,
    lng: 9,
    street: "aaa"
  }
}, {
  name: "b",
  address: {
    lat: 2,
    lng: 1,
    street: "bbb"
  }
}, {
  name: "c",
  address: {
    lat: 5,
    lng: 9,
    street: "ccc"
  }
}]

Output array should look like this. New object should contain lat, lng and array of gruped objects (without lat and lng in the adress)

[
  {
    lat: 5,
    lng: 9,
    items: [{
      name: "a",
      adress: {
        street: "aaa"
      }
    }, {
      name: "c",
      adress: {
        street: "ccc"
      }
    }]
  }, {
    lat: 2,
    lng: 1,
    items: [
      {
        name: "b",
        adress: {
          street: "bbb"
        }
      }
    ]
  }
]
makugym
  • 1
  • 1

3 Answers3

0
  • new array result
  • iterating over given array
  • getting key adress/lat and adress/lng
  • if a dict in result with same lat lng does exist do not add but adding the content to items array
  • else add a dict with lat lng and adding a list items and adding other stuff

usefull:

array[index] = value                 //setting entry
[key, value] of Object.entries(dict) //getting items
dict[key] = value                    //setting entry
delete dict[key]                     //remove entry
Hemera
  • 55
  • 1
  • 9
0

Maybe something like this:

const arr = [
  {
    name: "a",
    address: {
      lat: 5,
      lng: 9,
      street: "aaa"
    }
  },
  {
    name: "b",
    address: {
      lat: 2,
      lng: 1,
      street: "bbb"
    }
  },
  {
    name: "c",
    address: {
      lat: 5,
      lng: 9,
      street: "ccc"
    }
  },
  {
    name: "d",
    address: {
      lat: 5,
      lng: 9,
      street: "ddd"
    }
  }
];

const res = [];
arr.forEach((a) => {
  const { name, address } = a;
  const { lat, lng, ...rest } = address;

  const index = res.findIndex((v) => lat === v.lat && lng === v.lng);

  if (index >= 0) {
    res[index].items.push({
      name,
      adress: { ...rest }
    });
  } else {
    res.push({
      lat,
      lng,
      items: [
        {
          name,
          adress: { ...rest }
        }
      ]
    });
  }
});

console.log(res);
Kordrad
  • 1,154
  • 7
  • 18
0

Like this

const result = data.reduce((acc, item) => {
  const { lat, lng } = item.address;
  const latLngExists = acc.find(a => a.lat === lat && a.lng === lng);
  if (latLngExists) {
    latLngExists.items.push({
      name: item.name,
      address: { street: item.address.street }
    });
  } else {
    acc.push({
      lat,
      lng,
      items: [
        {
          name: item.name,
          address: {
            street: item.address.street
          }
        }
      ]
    })
  }
  return acc;
}, []);
AdityaParab
  • 7,024
  • 3
  • 27
  • 40