I’m trying to filter a property called ‘miles’ in an array of objects.
It should compare the value of the property ‘miles’ and return those only less than the user’s miles.
Next, push the value of the property ‘city’ into an empty array and return it.
I can’t get it to return the cities/countries as it’s just returning an empty array.
Here’s my code:
let flights = [{origin: 'AEP', destinations:[{city: 'PARIS', miles: 500}, {city: 'BOLZANO', miles: 200}, {city: 'DUBAI', miles: 400}]}, {origin: 'MXP', destinations: [{city: 'SAINT-TROPEZ', miles: 30}]},{origin: 'AEP', destinations: [{city: 'LISBON', miles: 30}, {city: 'MADRID', miles: 700}, {city: 'NICE', miles: 200}]}]
let user = {
name: 'Elena',
miles: 450,
origin: 'AEP'
}
function closureTrip(flights){
let list = [];
let array = [];
return function(user) {
for (let i = 0; i < flights.length; i++) {
if (flights[i].origin === user.origin) {
list.push(flights[i].destinations);
for (let j = 0; j < list.length; j++){
if(list[j].miles <= user.miles){
array.push(list[j].city);
}
return array
}
}
}
}
}
What I expected:
closureTrip(flights)(user) => [ 'BOLZANO', 'DUBAI', 'LISBON', 'NICE' ]
What I got:
closureTrip(flights)(user) => []
3
Answers
First, use filter to keep the entries with the correct origin. Then use flatMap to get all destinations from all of those entries in one array. Then, filter the destinations that aren’t too far. Finally, for each entry, return only the city property. The result will be an array.
You can do the following:
Array#filter
to get all elements in the array with the same origin as the user.Array#flatMap
to create a single one-dimensional array of all the cities from the previous step.Array#filter
again to get only the cities whose miles count does not exceed the user.Array#map
to extract only the names of those cities.filter
the flights whose origin matches the user.loop
in filtered flights andfilter
those flights whose destination miles are less than the user’s miles.map
the filtered destinations and keep only the city.merge
the result with the spread operator.Working demo-