Discovering the presence of two values within a single object array with the power of JavaScript

My challenge involves handling an array containing flight details such as origin, destination, and ticket cost. I am attempting to display the specific flight details for a given origin-destination pair. For instance: if the user chooses Bangalore as the origin and Delhi as the destination, I need to display the corresponding details. I utilized a set to obtain unique values. Is there a way to verify if the origin and destination belong to the same object so that it can display the object's details?

I experimented with the following code snippet, but it only checks the entire array.

 if((flightDetails.includes(orginVal)) && (flightDetails.includes(destinationVal))){
            alert("hello");
         }

Javascript code:

       flightDetails=[{
       "airline": "B-201",
       "from": "Bangaluru(BLR)",
       "to": "Delhi(DEL)",
       "detail": [{
         "date": "2019-12-30",
         "price": "3900",
         "departTime": "12:00 PM",
         "arriveTime": "14:00 PM",
         "seats":"10"
       }, {
         "date": "2019-12-31",
         "price": "3000",
         "departTime": "17:30 PM",
         "arriveTime": "19:30 PM",
         "seats":"3"
       }, {
         "date": "2019-06-01",
         "price": "2100",
         "departTime": "09:00 AM",
         "arriveTime": "11:00 AM",
         "seats":"7"
       }]
     },{
       "airline": "B-202",
       "from": "Delhi(DEL)",
       "to": "Bangaluru(BLR)",
       "detail": [{
         "date": "2019-12-30",
         "price": "3000",
         "departTime": "12:00 PM",
         "arriveTime": "14:00 PM",
         "seats":"10"
       }, {
         "date": "2019-12-31",
         "price": "3000",
         "departTime": "17:30 PM",
         "arriveTime": "19:30 PM",
         "seats":"3"
       }, {
         "date": "2019-06-01",
         "price": "2100",
         "departTime": "09:00 AM",
         "arriveTime": "11:00 AM",
         "seats":"7"
       }]
     }]

inputOrigin=document.getElementById('origin');
inputDesination=  document.getElementById("desination");
originOptions=document.getElementById('originCountry');
destinationOptions= document.getElementById('desinationCountry');

var originCategories = new Set();
var destinationCategories = new Set();

flightDetails.forEach((o) => originCategories.add(o.from));
originCategories = [...originCategories];

flightDetails.forEach((o) => destinationCategories.add(o.to));
destinationCategories = [...destinationCategories];


for(i=0;i<originCategories.length;i++) {
   originOptions.innerHTML+=' <option>'+originCategories[i]+'<option>';
}

for(i=0;i<destinationCategories.length;i++) {
   destinationOptions.innerHTML+=' <option>'+destinationCategories[i]+'<option>';
}

Answer №1

If you are looking for specific matches in an array, you can utilize the filter function. This will give you an array of all matching elements, from which you can extract the one you need.

var flightDetails=[{"airline": "B-201","from": "Bangaluru(BLR)","to": "Delhi(DEL)","detail": [{"date": "2019-12-30","price": "3900","departTime": "12:00 PM","arriveTime": "14:00 PM","seats":"10"}, {"date": "2019-12-31","price": "3000","departTime": "17:30 PM","arriveTime": "19:30 PM","seats":"3"}, {"date": "2019-06-01","price": "2100","departTime": "09:00 AM","arriveTime": "11:00 AM","seats":"7"}]},{"airline": "B-202","from": "Delhi(DEL)","to": "Bangaluru(BLR)","detail": [{"date": "2019-12-30","price": "3000","departTime": "12:00 PM","arriveTime": "14:00 PM","seats":"10"}, {"date": "2019-12-31","price": "3000","departTime": "17:30 PM","arriveTime": "19:30 PM","seats":"3"}, {"date": "2019-06-01","price": "2100","departTime": "09:00 AM","arriveTime": "11:00 AM","seats":"7"}]}];
     
var originVal = "Delhi(DEL)";
var destinationVal = "Bangaluru(BLR)"
var matches = flightDetails.filter(detail => detail.from === originVal && detail.to === destinationVal);
console.log(matches);

If your code is already capturing precise origins and destinations based on user input, using includes may not be necessary. It would be more suitable to search for exact matches instead.

The use of filter means that there could be multiple results, so consider providing the user with options to choose from the filtered list.

Answer №2

Instead of comparing a JavaScript object, compare the from-to strings.

To achieve this, utilize the find function and examine the attributes from-to for each object. This methodology will identify the first match rather than all matches; in such situations, consider using the filter function instead.

I anticipate that the end-user will input strings like originVal="Bangal" and destinationVal="Del"

let flightDetails = [{  "airline": "B-201",  "from": "Bangaluru(BLR)",  "to": "Delhi(DEL)",  "detail": [{    "date": "2019-12-30",    "price": "3900",    "departTime": "12:00 PM",    "arriveTime": "14:00 PM",    "seats": "10"  }, {    "date": "2019-12-31",    "price": "3000",    "departTime": "17:30 PM",    "arriveTime": "19:30 PM",    "seats": "3"  }, {    "date": "2019-06-01",    "price": "2100",    "departTime": "09:00 AM",    "arriveTime": "11:00 AM",    "seats": "7"  }]}, {  "airline": "B-202",  "from": "Delhi(DEL)",  "to": "Bangaluru(BLR)",  "detail": [{    "date": "2019-12-30",    "price": "3000",    "departTime": "12:00 PM",    "arriveTime": "14:00 PM",    "seats": "10"  }, {    "date": "2019-12-31",    "price": "3000",    "departTime": "17:30 PM",    "arriveTime": "19:30 PM",    "seats": "3"  }, {    "date": "2019-06-01",    "price": "2100",    "departTime": "09:00 AM",    "arriveTime": "11:00 AM",    "seats": "7"  }]}],
    originVal = "Bangaluru",
    destinationVal = "Delhi",
    found = flightDetails.find(({from, to}) => from.includes(originVal) && to.includes(destinationVal));

if (found) console.log(found.detail);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №3

Retrieve information by entering the input values for 'from' and 'to'

let flightDetails = [{"airline":"B-201","from":"Bangaluru(BLR)","to":"Delhi(DEL)","detail":[{"date":"2019-12-30","price":"3900","departTime":"12:00PM","arriveTime":"14:00PM","seats":"10"},{"date":"2019-12-31","price":"3000","departTime":"17:30PM","arriveTime":"19:30PM","seats":"3"},{"date":"2019-06-01","price":"2100","departTime":"09:00AM","arriveTime":"11:00AM","seats":"7"}]},{"airline":"B-202","from":"Delhi(DEL)","to":"Bangaluru(BLR)","detail":[{"date":"2019-12-30","price":"3000","departTime":"12:00PM","arriveTime":"14:00PM","seats":"10"},{"date":"2019-12-31","price":"3000","departTime":"17:30PM","arriveTime":"19:30PM","seats":"3"},{"date":"2019-06-01","price":"2100","departTime":"09:00AM","arriveTime":"11:00AM","seats":"7"}]}]

function getFlightDetails(){
  let fromInput = document.getElementById('from').value
  let toInput = document.getElementById('to').value
  let details = flightDetails.find(( {from,to} ) => from === fromInput && to === toInput)
  console.log(details)
}
<input id='from' placeholder='From'></input>
<input id='to' placeHolder='To'></input>
<button onClick=getFlightDetails()>Get Details</button>

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

Obtain the directory path of a node module

I am looking to retrieve specific files from an NPM package for my project. Currently, I am working with Vue and a validator, and I need to access a localization file for translation purposes. To import the validator, I have used the following standard c ...

Communication between the content script and background page in a chrome extension is not functioning correctly as intended

Displayed below is the code I posted: manifest.json { "manifest_version": 2, "name": "Demo", "description": "all_frames test", "version": "1.0", "background": { "scripts": ["background.js"] }, "content_scripts": [{ "matches": ...

When the mouse is passed over a span element within a div element

I am trying to implement a MouseOver function for the #AboutButton but the alert is not appearing. Can anyone provide insight into why this may be happening and suggest how to resolve it? --js code $(document).ready(function() { $('#AboutButton&apo ...

How to access class type arguments within a static method in Typescript: A clever solution

An issue has arisen due to the code below "Static members cannot reference class type parameters." This problem originates from the following snippet of code abstract class Resource<T> { /* static methods */ public static list: T[] = []; ...

The texture failed to load onto the 3D object during the mapping process

Issues with loading texture into the 3D ring model, although it works fine for other objects. No compile errors detected. Proper lighting conditions are set up but the color of the 3D model appears grey/black. The texture loads correctly for other object ...

Abort S3 file upload using ASW-SDK

Is there a way to abort an upload without raising an error Upload aborted. when calling upload.abort()? import { PutObjectCommandInput, S3Client } from '@aws-sdk/client-s3'; import { Progress, Upload } from "@aws-sdk/lib-storage"; cons ...

React: Dealing with null values when making a PUT request using axios

I have a list obtained from an external API through the use of axios. Each element in the list is an editable input field with its own corresponding update button. Upon modifying the data in an input, and while executing a PUT request to update it, consol ...

Having difficulty with C# and trying to extract data from XML using my generator

I abandoned Excel and created an XML file titled "ideas.xml" to store my data in the following format: <ideas> <verbs> <verb>Verb1</verb> <verb>Verb2</verb> <verb>Verb3</verb> <verb>Ver ...

Displaying form after Ajax submission

I have implemented an AJAX code to submit my form, but I am facing an issue where the form disappears after submission. Here is my current code: <script> $('#reg-form').submit(function(e){ e.preventDefault(); // Prevent Default Submissi ...

Click once to reveal, click twice to conceal the slider

I currently have a web page set up so that a single click on the text displays a slider for selecting a range of values. Now, I want to incorporate a feature where a double click will remove the slider. Below is the HTML code: <!DOCTYPE html> < ...

Altering the background hue of a div with jQuery based on its existing color

As someone new to jQuery, I have been delving into its intricacies and experimenting with it as much as possible. However, I am facing a time crunch and need to complete this project quickly. My question revolves around a particular issue... I have a link ...

The significance of Token Details in Tokbox

I'm currently working on developing a video chat platform that caters to various user roles - some may just observe while others actively participate in calls. I've been exploring the capabilities of the Tokbox Api () which allows metadata to be ...

Is there a way to retrieve all "a" tags with an "href" attribute that contains the term "youtube"?

My goal is to capture all a tags that have the href attribute containing the word youtube. This task requires the use of jquery. ...

"Incorporating splice in a for loop is causing issues and not functioning

I've been attempting to remove an item from an array, but for some reason, it's not working. Here's the code I'm using: vm.Continue = function () { $scope.invalidList = []; if (vm.errorexsist === true) { var table = doc ...

best method to retrieve all elements within a Perl array that fall between two specific values

My data consists of integer values that are each associated with a real value. This data can be represented as follows: 1 0.48 5 0.56 6 0.12 20 1.65 25 1.50 Only integers with associated values are included in the list. When given a range ...

Changing from localhost:3000/admin to localhost:3000 within the local server

I am currently developing a node.js application. My goal is to have the homepage rendered after the admin successfully uploads data, transitioning from localhost:3000/admin to localhost:3000. I attempted to achieve this using the code snippet below: route ...

Obtain the value of the input

I need assistance with the input below: <input value="25" data-hidden-value="25" name="associations[agencies][ids][]" data-hidden-name="associations[agencies][ids][]" class="string" type="hidden"> This particular input is generated dyna ...

Is it possible for me to interact with different elements upon hovering?

html, <div id="first"> <a>Click here</a> </div> <div id=second"> second div content </div> css, #first a:hover{ color:blue; /*change color on hover */ #second{ background:blue; } } In ...

What is the best way to activate a function to control animation transitions?

My goal is to manually control transitions in my HTML using JavaScript code, such as a tween library like TweenMax. Instead of relying on CSS for transitions with classes like .ng-enter, I want to target a JavaScript function: function onEnter() { /* tra ...

How can I ensure that the first static tab in the second menu is always selected based on the user's selection from the first tab?

I have two tabs menus, the first one is created dynamically and the second one has a static first tab with other tabs created dynamically using ng repeat. My question is how to make the first static tab in the second menu selected no matter what the user s ...