The function nested within a constructor that includes `this.route` is not assigning it as an array

 this.routeHandler = function () {
    let stations = ['KSFM', 'KPWM']
    let coordinates = [];
    let allCoords = [];
    if (Array.isArray(stations) == true) {
        for (let i = 0; i < fetchRoute().length; i++) {
            for (let j = 0; j < database.length; j++) {
                if (stations[i] === database[j].ident) {
                    coordinates = [(Number(database[j].coordinates[0])), (Number(database[j].coordinates[1]))];
                    allCoords.push(coordinates)
                }
            }
        }
        console.log(allCoords)

        return;
    } else { }

In my current implementation, I am able to retrieve the desired outcome - two sets of coordinates that match the input station array. However, what I truly desire is to have a dynamic array defined by this.route() instead of manually specifying "stations" in the code block. The issue arises from this route being part of a constructor and not directly accessible as an array.

The source of this array is related to airport(s) that are either singular or multiple additions, followed by appending the missing "K" letter prefix to incomplete airport identifiers. Despite consistently obtaining an array output, why does my this.routeCoord function fail to recognize it as such?

let database = [];

function apdata() {
    const url = "https://pkgstore.datahub.io/core/airport-codes/airport-codes_json/data/9ca22195b4c64a562a0a8be8d133e700/airport-codes_json.json";
    $.getJSON(url, function (data) {
        database = data;
        for (let i = 0; i < database.length; i++) {
            database[i].coordinates = database[i].coordinates.split(',');
        }
        runData();
    });
}
apdata();
let sampleArr = ['2020-08-08', 'N11682', 'KSFM', 'KSFM', 'KRKD KPSM', '', '', '', '', '', '', '3.0', '3.0', '0.0', '0.0', '0.0', '3.0', '161.70', '0', '0', '3', '3', '3', '0.0', '0.0', '0.00', '0.00', '0.00', '0.00', '0', '', '', '', '', '', '', '3.0', '0.0', '0.0', '0.0', '', '', '', '', '', '', '', '', 'false', 'false', 'false', 'Wayne'];

function runData() {
    console.log(flyData.route())
}



let flyData = new Flight(sampleArr[0], sampleArr[1], sampleArr[2], sampleArr[3], sampleArr[4], sampleArr[11]);


function Flight(Date, AircraftID, From, To, Route, TotalTime) {

    this.date = Date;
    this.aircraft = AircraftID;
    this.from = function () {
        if (From.length < 4) {
            return 'K' + From
        }
        else {
            return From
        }
    }
    this.to = function () {
        if (To.length < 4) {
            return 'K' + To
        }
        else {
            return To;
        }
    };
    this.route = function () {
        let stationList = [];
        if (Route.length > 4) {
            Route = Route.split(' ');
            for (let i = 0; i < Route.length; i++) {
                if (Route[i].length < 4) {
                    Route[i] = 'K' + Route[i]
                }
                stationList.push(Route[i])
            }

            return stationList
        } else if (Route.length < 4) {
            return 'K' + Route;
        } else {
            return Route
        }
    };
    let fetchRoute = this.route;
    this.time = TotalTime;
    this.toCoordinates = function () {
        for (let j = 0; j < database.length; j++) {
            if (this.to() === database[j].ident) {
                let coordinates = [(Number(database[j].coordinates[0])), (Number(database[j].coordinates[1]))];
                return coordinates;
            }
        }
    };
    this.fromCoordinates = function () {

        for (let j = 0; j < database.length; j++) {
            if (this.from() === database[j].ident) {
                return [(Number(database[j].coordinates[0])), (Number(database[j].coordinates[1]))];
            }
        }
    };

    this.routeHandler = function () {

        let coordinates = [];
        let allCoords = [];
        if (Array.isArray(this.route()) == true) {
            for (let i = 0; i < fetchRoute().length; i++) {
                for (let j = 0; j < database.length; j++) {
                    if (this.route()[i] === database[j].ident) {
                        coordinates = [(Number(database[j].coordinates[0])), (Number(database[j].coordinates[1]))];
                        allCoords.push(coordinates)
                    }
                }
            }

            return allCoords;
        } else {
            for (let j = 0; j < database.length; j++) {
                if (this.route() === database[j].ident) {
                    coordinates = [(Number(database[j].coordinates[0])), (Number(database[j].coordinates[1]))];
                }
            }
            return coordinates;
        }
    }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

What could be causing the discrepancy in my approach?

Answer №1

Optimize your program by caching the function return to ensure stability throughout its execution. The code contains potential side effects that could lead to unpredictability.

this.routeCoord = function () {
  let holding = this.route();
  let coord = [];
  let coords = [];
  if (Array.isArray(holding) == true) {
    for (let i = 0; i < tempRoute().length; i++) {
      for (let j = 0; j < database.length; j++) {
        if (holding[i] === database[j].ident) {
          coord = [
            Number(database[j].coordinates[0]),
            Number(database[j].coordinates[1]),
          ];
          coords.push(coord);
        }
      }
    }
    console.log(coords);

    return;
  } else { }
};

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

Tips for adjusting the button color in Material UI by utilizing the ":active" pseudo-class

In the project I am currently working on, I am incorporating Material UI. One of the tasks I need to complete is changing the active state of a button. I have implemented both hover and active states from Material UI in my code: const useStyles = makeStyle ...

Unable to directly assign a variable within the subscribe() function

My goal is to fetch a single row from the database and display its information on my webpage. However, I've encountered an issue with the asynchronous nature of subscription, which prevents immediate execution and access to the data. Upon running the ...

Merging and collaborating on a variety of JSON documents

I have limited experience working with JSON files and I'm facing some challenges. The software I'm using generates a separate JSON file for each image it processes, resulting in hundreds of individual JSON files at any given time. My main struggl ...

Exploring the capabilities of IBM Integration Bus in handling JSON parsing operations

Hello, I am currently facing an issue with parsing JSON data in the IIB Toolkit. The error message thrown by the java compute node is: "java.lang.NoClassDefFoundError: org.json.JSONObject" When attempting to parse incoming JSON messages using UTF-8 encodi ...

An innovative countdown clock for WooCommerce that dynamically displays delivery time as a customizable shortcode

After successfully creating a Wordpress shortcode with a JavaScript counter, I encountered an issue: Back End - Counter functions properly: https://i.stack.imgur.com/qyHIL.png Front End - Counter not working (no console errors...): https://i.stack.imgu ...

Take out a specific element from an array consisting of multiple objects

I have a specific array structure and I need to remove elements that match a certain criteria. Here is the initial array: const updatedUsersInfo = [ { alias: 'ba', userId: '0058V00000DYOqsQAH', username: '<a href=" ...

iPhone App Utilizing Twitter-JSON Parsing

Struggling with parsing JSON used to be a challenge for me until I discovered an excellent tutorial that guided me through the process. While creating my own web services to parse JSON, I followed the same steps successfully. However, when attempting to pa ...

Differences between count() and length() methods in Protractor

When it comes to determining the number of elements inside the ElementArrayFinder (which is the result of calling element.all()), you have two options according to the documentation: $$(".myclass").length, detailed here: This approach involves using ...

Issue with bidirectional binding on angular material slide toggle not functioning as anticipated (Angular 4)

My angular material slide-toggle implementation seems to be working, but I'm facing an issue where it doesn't bind the value to the relevant variable as expected. // other irrelevant imports above.. import {MatDialog, MatDialogRef, MAT_DIALOG_DA ...

error encountered when trying to parse JSON due to an incorrect identifier

While putting together a dbt base model, I encountered an error message as shown below. It seems like there might be a small syntax error at line 6 that I am unable to identify. 15:40:22 Database Error in model base_datacenter_handling_unit (models/l10_st ...

When using SweetAlert2, a single button will automatically be highlighted as soon as the modal opens

I recently made the switch from using SweetAlert to SweetAlert 2. It took some time to get used to, but I finally achieved my desired outcome, with one small exception. Upon opening the modal, if there is only one button and no other inputs, the button ap ...

Unable to assign to array in VBA

There seems to be an issue in my code that I can't figure out. Specifically, the line "Key = decode.GetKeys(issue)" is causing the error mentioned in the title of this question. Public Sub Import_JSON_From_URL(url As JiraJSONGet) ThisWorkbook.Sheets ...

Axios - Show the error message returned from validation as [object Object]

Within my API, I include the following validation logic: $request->validate([ 'firstname' => 'required', 'lastname' => 'required', 'username' => 'required|unique:us ...

How can I add a JSON object to another JSON object in a React application?

How can I merge two JSON objects in reactjs? Here is the initial JSON format: First JSON Object: { "results": { "Action": "Success!" }, "report": { "Strategy": "Yes", ...

Incorporate custom JavaScript files that contain classes within a Vue component

i am encountering an issue with a js file that contains classes with functions. i have a vue component and i want to create an instance of that class within it. (when directly copying the file into my <script> tag, everything works smoothly) myfile. ...

AngularJS bracket-enhanced template

Why is AngularJS giving an error when brackets are used inside ng-template content? I am trying to create an input field that should accept an array, but I keep getting this error message: "Error: Syntax Error: Token ']' not a primary expression ...

Can const variables be reassigned in JavaScript programming?

Can you reassign a const variable in JavaScript? In C++, we can cast variables to and from const. Is there something similar in JavaScript? My question is const a = 1; unconst(a); a = "xyz"; a === "xyz" // true I'm not referring to object prope ...

Strange behavior of the .hasOwnProperty method

When attempting to instantiate Typescript objects from JSON data received over HTTP, I began considering using the for..in loop along with .hasOwnProperty(): class User { private name: string; private age: number; constructor(data: JSON) { ...

Serializing MongoDB, JSON objects, and dictionary members

Imagine having a class structured like this: class A { Dictionary<string, string> Dict1 { get; set } } Now, when serializing it to Json, you want the output to be: "A" : {"strKey1" : "strVal1", "strKey2" : "strVal2"} instead of: "A" : { "Dict ...

Leveraging AngularJS ngBind with a JavaScript object

Within the given string, integrating a javascript object and embedding it into an ngBinding does not result in proper evaluation. I have a string where I want to incorporate a specific part of a javascript object and am transitioning to Angular for its use ...