I have an array of objects which contain addresses. I need to perform the following:
- Extract each postcode from address values.
- Find unique postcodes and store amount of duplicates.
- Store the first address for each unique postcode in a new array along with the number of duplicates.
Here is my current code.
const json = [
{ "id": "10093729341", "address": "1 Alpha Road CF14 6AA" },
{ "id": "10024750520", "address": "2 Alpha Road CF14 6AA" },
{ "id": "10025738368", "address": "3 Alpha Road CF14 6AF" },
{ "id": "10025738368", "address": "4 Alpha Road CF14 6AF" },
{ "id": "10025738368", "address": "4 Alpha Road CF14 6AB" }
]
let allPostcodes = [];
json.forEach(address => {
const fullAddresses = address.address;
const postcodes = fullAddresses.split(",").map(s => s.trim().match(/([A-Za-z]{1,2}\d{1,2})(\s?(\d?\w{2}))?/)).filter(e => e)[0][0]
allPostcodes.push(postcodes);
});
const uniquePostcodes = [...new Set(allPostcodes)];
uniquePostcodes.forEach(postcode => {
const addresses = json.find(address => address.address.indexOf(postcode));
console.log(addresses.address);
});
The final part above stops at the first match but for the first postcode only. I thought that in a loop it would work but it doesn't.
My desired outcome would be this:
const array = [
{
"address": "1 Alpha Road CF14 6AA",
"count": 2,
"postcode": "CF14 6AA"
},
{
"address": "3 Alpha Road CF14 6AF",
"count": 2,
"postcode": "CF14 6AF"
},
{
"address": "4 Alpha Road CF14 6AB",
"count": 1,
"postcode": "CF14 6AB"
}
]