I am trying to solve a difficult computation but i am not reaching anywhere. can someone please help
Here is a simple example.
const filterCityBy = "NY";
const data = [
{ name: "Harry, age: 45, city: "NY" },
{ name: "Mike, age: 36, city: "CA" }
]
const filteredData = data.filter(x = x.city === filterCityBy);
output = [ { name: "Harry, age: 45 } ]
This is self explainatory. I am trying to filter data
with value filterCityBy
and getting the desired output
But my requirement is as follows
const filterCityBy = "NY";
const data = [
{ name: "Harry, age: 45, totalCities: [{ city: "NY"}]},
{ name: "Mike, age: 36, totalCities: [{ city: "NY"}, {city: "CA"} }] }
]
output = [ { name: "Harry, age: 45 }, { name: "Mike, age: 36 } ]
How can i achieve the desired output. Harry and Mike both has city as NY
in their totalCities
array. I only need their name
and age
once the city is present in their totalCities
array.
Can someone please help on how to get this.
3
Answers
Combine
filter()
withsome()
to check if some of thetotalCities
matchesfilterCityBy
.Then use
map()
to get only thename
andage
key by removingtotalCities
using a destructuring assignment (...r
):You could filter the array and map the result without
totalCities
.Check your example code and result. The
filter
method alone would not give that result once you fix the code. You would need themap
method as well, as pointed out by others already. Here is another way you can do it: