I am trying to filter unique object from the places Array inside the list Array, but not able to get the exact solution to find the unique place name, please find the array data below=>
"list":[
{
"id":1,
"uID": 1
"places":[
{
"name":"USA"
},
{
"name":"USA"
},
{
"name":"GER"
}
]
},
{
"id":2,
"uID":2
"places":[
{
"name":"USA"
},
{
"name":"GER"
},
{
"name":"GER"
}
]
}
]
The Expected output should be like this =>
"list":[
{
"id":1,
"uID": 1
"places":[
{
"name":"USA"
},
{
"name":"GER"
}
]
},
{
"id":2,
"uID":2
"places":[
{
"name":"USA"
},
{
"name":"GER"
}
]
}
]
Appreciate your help.
You can use Array.map() to map to map each member of the list to a new value.
For each value, we can remove duplicate places using a Set object.
We instantiate the Set using an array of the place names, using .map() again. The Set will then contain a list of the unique place names.
We then assign this to the places property of each output item.
const list = [ { "id":1, "uID": 1, "places":[ { "name":"USA" }, { "name":"USA" }, { "name":"GER" } ] }, { "id":2, "uID":2, "places":[ { "name":"USA" }, { "name":"GER" }, { "name":"GER" } ] } ]
const result = list.map(({ places, ...obj }) => {
const uniquePlaces = new Set(places.map(item => item.name));
return { ...obj, places: [ ...uniquePlaces].map(name => ({ name })) }
})
console.log('Result:', result);
.as-console-wrapper { max-height: 100% !important; }
You can use Set() to filter duplicate by using add() method.
for more reference take a look at this link : https://levelup.gitconnected.com/how-to-find-unique-values-by-property-in-an-array-of-objects-in-javascript-50ca23db8ccc
places array as (JSON) string via JSON.stringify().new Set() to distinct the JSON string.Array.from().JSON.parse().list = list.map(x => {
x.places = Array.from([...new Set(x.places.map(x => JSON.stringify(x)))])
.map(x => JSON.parse(x));
return x;
})