Steps for iterating through an object and using an if statement to verify a property's value

My challenge involves filtering a property named 'miles' within an array of objects. The objective is to compare the 'miles' property value and only return those that are less than the user's specified miles. Subsequently, the values of the 'city' property should be pushed into an empty array and returned.

However, the current issue is that the code is returning an empty array instead of the desired cities/countries.

Below is the code snippet provided:

/* Your provided code snippet here */

Expected Output:

closureTrip(flights)(user) => [ 'BOLZANO', 'DUBAI', 'LISBON', 'NICE' ]

Current Output:

closureTrip(flights)(user) => []

Answer №1

Here are the steps you can take:

  1. Utilize Array#filter to retrieve all elements in the array that share the same origin as the user.
  2. Employ Array#flatMap to form a single one-dimensional array containing all the cities from the previous step.
  3. Apply Array#filter once more to select only the cities whose mile count is within the user's limit.
  4. Use Array#map to extract solely the names of those cities.

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) {
    return user => 
      flights.filter(f => f.origin === user.origin).flatMap(f => f.destinations)
             .filter(o => o.miles <= user.miles).map(o => o.city);
}
console.log(closureTrip(flights)(user));

Answer №2

To start, utilize the filter function to select only the entries with the correct origin. Next, apply flatMap to retrieve all destinations from those entries and consolidate them into a single array. Then, filter out any destinations that are beyond a certain distance. Lastly, extract and return the city property for each entry. The output will be an array of cities.

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'
}

console.log(
  flights.filter(i => i.origin===user.origin)
    .flatMap(i => i.destinations)
    .filter(i => i.miles <= user.miles)
    .map(i => i.city)
)

Answer №3

  1. identify the flights that have the same origin as the user.
  2. iterate through the filtered flights and select those with destinations closer than the user's travel distance.
  3. extract only the city names from the filtered destinations.
  4. combine the extracted cities using the spread operator.

Demonstration of concept-

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'
}

let result = [];
flights.filter(f => f.origin == user.origin).forEach(f => {
  let r = f.destinations.filter(d => d.miles < user.miles).map(i => i.city)
  result = [...result, ...r]
})

console.log(result)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn the step-by-step process of cropping and zooming an image using the react-image-crop

I am looking to implement zooming and cropping functionality for an image using react-image-crop instead of react-easy-crop. Currently, the cropping does not take into account the zoom level set by ReactCrop's scale property. I want to be able to zo ...

Error message signaling that the dollar sign symbol is not defined in the Laravel framework

Hello there, I'm currently learning Laravel and following a tutorial on building a student CMS. I have integrated a datepicker and a bootstrap modal that are supposed to pop up when clicking form buttons. However, despite everything appearing correct, ...

Troubles arise when trying to compile Typescript and React with esbuild

I set out to create a new package and upload it to npm, starting with a demo package first. I began by using this repository as a foundation: https://github.com/wobsoriano/vite-react-tailwind-starter After that, I made updates to the build script: " ...

Access a SQL database to retrieve a data value and seamlessly integrate it into an HTML document with the help of node

I am new to web development and currently facing a challenge in displaying SQL content on an HTML page. My stack includes Node.js, Express, and SQLite3. I have a folder named public containing HTML, CSS, and JS files. The objective is to retrieve a varia ...

Excessive delay in executing Javascript loops

While developing an EMI calculator for a hybrid mobile app, I encountered a performance issue. The execution within one of the loops takes too long, resulting in the page becoming unresponsive. Here is my code snippet: var EMICalculator = { basicEMI: fun ...

React-virtualized list experiencing performance problems due to react-tether integration within its elements

Description I need help with a challenging issue. I have a long list of items displayed in a react-virtualized VirtualScroll. Each item on the list contains many elements, including one that triggers a context menu. I'm using react-tether to attach t ...

The functionality of `config.assets.debug = true` fails to

I've encountered an issue with the configuration on development where config.assets.debug = true doesn't seem to work correctly. Instead of having multiple separate JavaScript and CSS file inclusions, I'm getting a consolidated one: <li ...

When you drag down on mobile Safari on an iPad, touch events may cease to fire in HTML5

When I implement event listeners to handle touch events like touchmove and touchstart document.addEventListener("touchstart", function(event){ event.preventDefault(); document.getElementById("fpsCounter").innerHTML = "Touch ...

Is there a way to open a particular Bootstrap tab within a modal using a URL?

I am seeking a way to automatically open a specific tab within a modal using its URL. To achieve this, I have included the following JavaScript code at the end of my website. By entering website.com/#modal-6 in the browser, it will open with modal-6 activa ...

"The ng-route feature is not working as expected; instead of displaying the template url, it is showing

I'm currently developing a voting application as part of my freecodecamp project using the MEAN stack. I have completed the backend portion, but without user authentication for now. My focus now is on the frontend. I have created an HTML page that li ...

How can I activate a function or pass a selected value to a different scope variable using AngularUI Bootstrap Datepicker?

Check out this AngularUI Datepicker demo on Plunker: http://plnkr.co/edit/DWqgfTvM5QaO5Hs5dHco?p=preview I'm curious about how to store the selected value in a variable or trigger another function when a date is chosen in the field. I couldn't ...

Override existing Keywords (change false to true)

Are there any ways to overwrite reserved words? It's not something I would typically consider, but it has sparked my curiosity. Is it feasible to set false = true in JavaScript? I've come across instances on different websites where individuals ...

Trouble with Chakra UI loading Images from local sources

I'm running into issues when trying to load local images using the Chakra UI library in combination with Next.js. <Image src="./homepage/footer/Black.svg" /> Here is the current folder structure: When checking my console, I see the f ...

Creating multiple div elements with changing content dynamically

I am facing an issue with a div named 'red' on my website where user messages overflow the 40px length of the div. To prevent this, I want to duplicate the 'red' div every time a message is sent so that the messages stay within the boun ...

Navbar in bootstrap appears to be flashing when it is in its expanded

Example Link On smaller screens, the bootstrap navbar menu does not collapse by default when clicking on a menu item. To fix this issue, I added attributes data-toggle="collapse" and data-target="#navbar-collapse" to each menu item so that the menu will ...

Obtain the text that is shown for an input field

My website is currently utilizing Angular Material, which is causing the text format in my type='time' input field to change. I am looking for a way to verify this text, but none of the methods I have tried give me the actual displayed text. I a ...

How to stop Mouseenter event from bubbling up in an unordered list of hyperlinks using Vue 3

I've experimented with various methods to prevent event bubbling on the mouseenter event, but I'm still encountering an issue. When I hover over a link, the event is triggered for all the links as if they were all being hovered over simultaneousl ...

Is there a way to send JSON using ExpressJS in UTF-8 encoding?

Currently facing an issue with my new web app that I haven't encountered in the past. Experimenting with a simple code snippet like this: var jsonToSend = {hello: "woørld"}; app.get('/someUrl', function(req, res) { res.setHeader('Co ...

Elements in Motion

Working on a parallax effect, I've managed to assign unique scroll speeds to (almost) every element. Moreover, these elements are programmed not to activate their scroll speed until they enter the viewport. Below is the JavaScript code for trigger co ...

Unable to load files in Handlebars when using Node and Express

Currently, I am in the process of developing a Node/Express web application for basic CRUD operations. However, I am encountering difficulties incorporating Handlebars into my project. Whenever I attempt to utilize Handlebars, none of the stylesheets from ...