I have an array of objects here:
const users = [
{
name: 'xyz',
claims: [
{"location": 'dallas',
"id": '123'},
{"location": 'frisco',
"id": '123'},
{"location": 'plano',
"id": '123'},
]
},
{
name: 'abc',
claims: [
{"location": 'richardson',
"id": '123'},
{"location": 'rowlett',
"id": '123'},
{"location": 'dallas',
"id": '123'},
]
},
{
name: 'adr',
claims: [
{"location": 'frisco',
"id": '123'},
{"location": 'irving',
"id": '123'},
{"location": 'dallas',
"id": '123'},
]
}
]
I want to get all the locations with dallas as the value. How can I do that? I know I would probably use a loop (maybe a forEach) but I am not exactly sure how I could get the values that I need. Would I use filter?
asked Aug 26, 2022 at 20:39
aquile hollins
1732 silver badges14 bronze badges
2 Answers 2
You can use flatMap to flatten the mapped array after filtering the locations which equal to dallas.
const users = [
{
name: 'xyz',
claims: [
{"location": 'dallas',
"id": '123'},
{"location": 'frisco',
"id": '123'},
{"location": 'plano',
"id": '123'},
]
},
{
name: 'abc',
claims: [
{"location": 'richardson',
"id": '123'},
{"location": 'rowlett',
"id": '123'},
{"location": 'dallas',
"id": '123'},
]
},
{
name: 'adr',
claims: [
{"location": 'frisco',
"id": '123'},
{"location": 'irving',
"id": '123'},
{"location": 'dallas',
"id": '123'},
]
}
]
const result = users.flatMap(u => u.claims.filter(c => c.location === 'dallas'))
console.log(result)
answered Aug 26, 2022 at 20:48
Mina
17.8k3 gold badges24 silver badges39 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
aquile hollins
Thanks for this. I failed a interview for not knowing this lol I was trying to filter and that’s it. I see where I went wrong and I will never forget the use case for flatMap again!
Mina
You are welcome, Never mind about the interview, and try to train on arrays high order methods, like
flat, flatMap, filter, reduce, reduceRight, map, forEach, some, every and try to know the uses of each of them, and I wish you good luck in the next interview.Use flatMap with combination of filter:
const dallasLocations = users.flatMap(user => {
return user.claims.filter(claim => claim.location === 'dallas')
})
Comments
lang-js
I want to get all the locations with dallas as the value<- What do you want to get exactly? Theid?users.map(u => u.claims).flat().filter(c => c. location === 'dallas')