Home > Enterprise >  Find all urls for each array value
Find all urls for each array value

Time:06-26

Given the following array structure:

{ url: "www.site.com", ids: ["F20", "C10", "C05"] }, { url: "www.site.com/something", ids: ["F20", "C06", "C05"] }, { url: "www.site.com/somethingelse", ids: ["F21", "C12", "C05"] }

I’m trying to loop over the array and find all urls for each id. So the end result would group the urls where an id value has the same url:

F20 for instance would have www.site.com and www.site.com/something.

The data structure would end up being an array of objects where each id would have an array of urls in which the id exists.

I have started with a basic for loop, but stuck on the best way to loop over and check the url for each value of the array it’s associated with and then group by id.

for(id of ids){ console.log(id) }

The end result would be a list of ids with all associated urls where that id appears.

CodePudding user response:

You can loop over input array and then loop over ids for each input element and keep adding urls for corresponding ids. For e.g.

const input = [{ url: "www.site.com", ids: ["F20", "C10", "C05"] }, { url: "www.site.com/something", ids: ["F20", "C06", "C05"] }, { url: "www.site.com/somethingelse", ids: ["F21", "C12", "C05"] }]
const output = {}
input.forEach(obj=>{
    const ids = obj.ids
    if(ids && ids.length>0){
        ids.forEach(id=>{
            if(!output[id]){
                output[id] = []
            }
            output[id].push(obj.url)
        })
    }
})

for(let id of Object.keys(output)){
    console.log(`${id}:${JSON.stringify(output[id])}`)
}
  • Related