My use case is something like this.
- I have an array of objects called locations.
- It contains information about Provinces, Districts and cities.
- City belongs to a District, District belongs to a Province.
- If
parent_region_idnullmeans it is a province. - If
parent_region_idis a province's id means it is a district. - Otherwise it's a city.
My goal is to filter out all the cities from the array. I did a odd way and it works though.
But I would like to know what is most optimal way to do this? This is my working code.
const locations = [
{id:1,name:"Western province",parent_region_id:null},
{id:2,name:"Southern province",parent_region_id:null},
{id:3,name:"Central province",parent_region_id:null},
{id:4,name:"Colombo district",parent_region_id:1},
{id:5,name:"Galle district",parent_region_id:2},
{id:6,name:"Kandy district",parent_region_id:3},
{id:7,name:"Maharagama",parent_region_id:4},
{id:8,name:"Nugegoda",parent_region_id:4},
{id:9,name:"Peradeniya",parent_region_id:6},
]
//get the province ids first
const provinces = []
locations.forEach(e=> {
if(!e.parent_region_id){
provinces.push(e.id)
}
})
// get all the districts then
const districts = []
locations.forEach(e=>{
if(provinces.includes(e.parent_region_id)){
districts.push(e.id)
}
})
//get cities
const cities = [];
locations.forEach(e=>
{
if(!districts.includes(e.id) && !provinces.includes(e.id)){
console.log(e.name," is a city")
}
})