I have an array of objects like below, which inside of it has another array of objects which has duplicate verticalName values that need to be removed in order to be displayed on the page.
"landingPages": [
{
"programmes": [
{
"progName": "Programme 1",
"verticals": [
{
"id": "8",
"verticalName": "Law and Criminology"
}
]
}
]
},
{
"programmes": [
{
"progName": "Programme 2",
"verticals": [
{
"id": "1",
"verticalName": "Psychology and Sociology"
}
]
}
]
},
{
"programmes": [
{
"progName": "Programme 3",
"verticals": [
{
"id": "3",
"verticalName": "Computing and IT"
}
]
}
]
},
{
"programmes": [
{
"progName": "Programme 4",
"verticals": [
{
"id": "1",
"verticalName": "Psychology and Sociology"
}
]
},
{
"progName": "Programme 5",
"verticals": [
{
"id": "3",
"verticalName": "Computing and IT"
}
]
},
{
"progName": "Programme 6",
"verticals": [
{
"id": "2",
"verticalName": "Business and Management"
}
]
},
{
"progName": "Programme 7",
"verticals": [
{
"id": "3",
"verticalName": "Computing and IT"
}
]
},
{
"progName": "Programme 8",
"verticals": [
{
"id": "3",
"verticalName": "Computing and IT"
}
]
}
]
}
]
I have tried couple of solutions, some of the did not work but one did, which I copy/pasted below. I've managed to store all of them inside of one array of objects, it's just that the code to me looks really bad. I am trying to find a cleaner solution to this problem. Here is my solution and I would like to see how does it compare to your solutions maybe, and if you could give me some feedback that would be amazing.
let known = {}
let noduplicates = programmes.map((subarray) => {
const newarrays = []
subarray.verticals.forEach((item) => {
if (
!known.hasOwnProperty(item.verticalName) &&
(known[item.verticalName] = true)
) {
newararys.push(item)
} else {
console.log('test')
}
})
console.log(newarrays)
return newarrays
})
const fil = filtered.filter((item) => item.length)
const singleArr = fil.reduce((a, b) => a.concat(b), [])
console.log(singleArr)
What I am trying to get is something like this, basically, just all the objects that were found inside of verticals array, but - without duplicates:
[
{id: "1", verticalName: "Psychology and Sociology"},
{id: "3", verticalName: "Computing and IT"},
{id: "2", verticalName: "Business and Management"}
]
Cheers everyone!