Nested for loops utilized to organize items

I'm struggling with implementing a nested for loop to sort items in an array. Unfortunately, I'm encountering an issue where some values are being duplicated and I can't seem to identify the root cause of the problem. My logical reasoning skills are not fully developed yet. Even though I am aware of using built-in sorting functions, this task is a part of my school assignment which requires the use of two for loops. My intention is to utilize the "order" key value to determine the position of objects in the array.

 var connection = await fetch('momondo.php')
  var jData = await connection.json()
  var aScheduleInOrder = jData
  for (var i = 0; i < jData.length; i++) {           

    for (var j = 0; j < jData[i].schedule.length; j++) {

      aScheduleInOrder[i].schedule[jData[i].schedule[j].order] = jData[i].schedule[j]
    }
  }

Below are the JSON objects contained in the jData:

[  
  {     
  "currency":"DKK",
  "price":3000,
  "schedule":
  [    
    {"airlineIcon":"LH.png", "date":1581513600,"id":"SAS22","from":"C", "to":"D","waitingTime":120,"flightTime":240,"order":2},
    {"airlineIcon":"KL.png","date":1581510000, "id":"SAS33","from":"B", "to":"C","waitingTime":60,"flightTime":180,"order":1},
    {"airlineIcon":"DY.png","date":1581501600,"id":"SAS1","from":"A", "to":"B","waitingTime":0,"flightTime":80,"order":0}
  ]
},

{   
  "currency":"DKK",
  "price":5000,
  "schedule":
  [
    {"airlineIcon":"LX.png", "date":1581513600,"id":"SAS55","from":"B", "to":"C","waitingTime":120,"flightTime":240,"order":1},
    {"airlineIcon":"SK.png","date":1581501600,"id":"SAS44","from":"A", "to":"B","waitingTime":0,"flightTime":80,"order":0}

  ]
},

{     
  "currency":"DKK",
  "price":15000,
  "schedule":
  [
    {"airlineIcon":"AC.png","date":1581501600,"id":"SAS78","from":"A", "to":"B","waitingTime":0,"flightTime":80,"order":0}
  ]
}    
]

In the array at position [1], within the schedule array, the first item at position [0] has an "order" key with a value of 1. According to my logic utilizing two for loops, this item should be moved to position [1], and subsequent items should follow suit accordingly. The updated order should resemble the following structure:

[  
  {     
  "currency":"DKK",
  "price":3000,
  "schedule":
  [
    {"airlineIcon":"DY.png","date":1581501600,"id":"SAS1","from":"A", "to":"B","waitingTime":0,"flightTime":80,"order":0},
    {"airlineIcon":"KL.png","date":1581510000, "id":"SAS33","from":"B", "to":"C","waitingTime":60,"flightTime":180,"order":1},
    {"airlineIcon":"LH.png", "date":1581513600,"id":"SAS22","from":"C", "to":"D","waitingTime":120,"flightTime":240,"order":2}
  ]
},

{   
  "currency":"DKK",
  "price":5000,
  "schedule":
  [
    {"airlineIcon":"SK.png","date":1581501600,"id":"SAS44","from":"A", "to":"B","waitingTime":0,"flightTime":80,"order":0},
    {"airlineIcon":"LX.png", "date":1581513600,"id":"SAS55","from":"B", "to":"C","waitingTime":120,"flightTime":240,"order":1}
  ]
},

{     
  "currency":"DKK",
  "price":15000,
  "schedule":
  [
    {"airlineIcon":"AC.png","date":1581501600,"id":"SAS78","from":"A", "to":"B","waitingTime":0,"flightTime":80,"order":0}
  ]
}      
]

Your assistance in resolving this dilemma would be greatly appreciated :)

Answer №1

Okay, so if I understand correctly, you only want to sort the order attribute and not the items inside the array? In that case, you can add the following line in your second nested loop:

aScheduleInOrder[i].schedule[j].order = j;

Instead of:

aScheduleInOrder[i].schedule[jData[i].schedule[j].order] = jData[i].schedule[j]

UPDATE: Given the changes made to the original question, here is a revised solution. Please use this code snippet, as it will generate a new array by retrieving the correct scheduling order from the initial array. It's also easily understandable from an educational standpoint:

for (var i = 0; i < jData.length; i++) {

    var currency = jData[i].currency;
    var price = jData[i].price;
    var schedule = [];

    var data = {
        "currency": currency,
        "price":    price,
        "schedule" : []
    };

    for (var j = 0; j < jData[i].schedule.length; j++) {
        data.schedule[j] = getScheduleByOrder(jData[i].schedule,j);
    }

    aScheduleInOrder.push(data);
}

function getScheduleByOrder(scheduleArray,order){

    for (var k = 0; k < scheduleArray.length; k++) {
        if (scheduleArray[k].order === order){
            return scheduleArray[k];            
        }
    }   
}

Answer №2

Have you considered utilizing the .sort() Array method? EDIT : Oh,

this requirement is part of a school assignment and we must incorporate two for loops.
School assignments are the best!

let jData = [{
    "currency": "DKK",
    "price": 3000,
    "schedule": [{
        "airlineIcon": "SK.png",
        "date": 1581501600,
        "id": "SAS1",
        "from": "A",
        "to": "B",
        "waitingTime": 0,
        "flightTime": 80,
        "order": 0
      },
      {
        "airlineIcon": "KL.png",
        "date": 1581510000,
        "id": "SAS33",
        "from": "B",
        "to": "C",
        "waitingTime": 60,
        "flightTime": 180,
        "order": 1
      },
      {
        "airlineIcon": "LH.png",
        "date": 1581513600,
        "id": "SAS22",
        "from": "C",
        "to": "D",
        "waitingTime": 120,
        "flightTime": 240,
        "order": 2
      }
    ]
  },

  {
    "currency": "DKK",
    "price": 5000,
    "schedule": [{
        "airlineIcon": "SK.png",
        "date": 1581501600,
        "id": "SAS1",
        "from": "A",
        "to": "B",
        "waitingTime": 0,
        "flightTime": 80,
        "order": 1
      },
      {
        "airlineIcon": "LH.png",
        "date": 1581513600,
        "id": "SAS22",
        "from": "B",
        "to": "C",
        "waitingTime": 120,
        "flightTime": 240,
        "order": 0
      }
    ]
  },

  {
    "currency": "DKK",
    "price": 15000,
    "schedule": [{
      "airlineIcon": "SK.png",
      "date": 1581501600,
      "id": "SAS1",
      "from": "A",
      "to": "B",
      "waitingTime": 0,
      "flightTime": 80,
      "order": 0
    }]
  }
];

jData = jData.map( obj => {
    obj.schedule.sort( (a,b) => a.order > b.order ? 1 : -1); // sort by the "order" key ascending
    return obj;
})

console.log(jData)

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

Placing objects in an array results in the inclusion of numerous null values

Having trouble assigning an object to an array by key, as it is resulting in multiple null values alongside the actual object. To start off, I am outputting data to an HTML data-* attribute using PHP: <div id="{{$obj_id}}" data-my-obj="{ ...

Concentrate on all elements within the form

I am in the process of developing a form with multiple input fields, one of which is shown below. I am interested in triggering an event using jQuery's focusout function. The form goes by the name: form_test <form id="form_test"> <input ...

What is the best method to retrieve a secure httponly cookie in a Next.js application?

Our next JS application is making a request to The backend team has configured the response cookie as a secure HttpOnly cookie. const session = await ( await fetch( `https://demo.com/auth/session`, requestOptions )).json(); console.log(&qu ...

When executing JavaScript code, the file remains unchanged and does not alter the URL

I want my form to check a SQL database upon submission and execute a JavaScript file that captures the data into a constant. However, instead of running the JS script on the page as desired, it redirects to a new URL. Is there a way to ensure that the JS ...

To access a form element in JavaScript function, utilize the dynamic form name approach

Currently, I am facing an issue with a JavaScript alert function where I am trying to view the HTML form URL before it is submitted. Following advice from a post on StackOverflow about retrieving form submit content before submit, I attempted to implement ...

The integration of Meteor.js with an external Mongo database is causing issues with logging in to Mongo

In my project, I am using a meteor.js application along with mongo db (2.6). To create a user in mongo, I followed these steps: use meteor db.createUser( { user: "meteor", pwd: "password", roles: [ { role: "userAdmin", ...

What is the best way to ensure a cron job executing a Node.js script can access variables stored in an .env file?

Currently, I have a scheduled job using cron that runs a Node.js script. This script utilizes the dotenv package to access API keys stored in a .env file. Running the Node.js script from the command line retrieves the variables from the .env file successf ...

Guide to implementing a feature where clicking on a specific section of the background image triggers a transition to another website using HTML

Is it possible to set up a background image with clickable regions that direct users to specific websites? ...

Decoding a complex nested JSON file using a JSON parser

Struggling to interpret the contents of this json file {"window":60,"version":200,"timestamp":1582886130,"body":{"totals":{"count":1,"offset":0},"audio_clips":[{"id":7515224,"title":"The West Ham Way Podcast - We`re back!","description":"This is a message ...

The command 'vue' is not a valid internal or external command

After ensuring that everything was installed correctly, I encountered an issue when trying to create a project. An error message would appear stating that "'vue' is not recognized as an internal or external command". I attempted to reinstall the ...

Validating JSON response in JMeter with multiple data points

Can anyone assist me with validating this response? I have a response containing currency values and I need to validate them. How can I achieve this? Any help is appreciated. Thank you. Response: { "uid": "123-321", "period" ...

Clicking our way back through the loop

Looking to display a name when each item is clicked. I've assigned an ID to each element, but it seems like I'm overlooking something. In the current code, I'm thinking there should be a variable involved, but I'm uncertain: $(document ...

Modifying the app.css file in the source tab of dev tools does not cause any changes in the DOM when working with a

Just starting out with react js here. While exploring developer tools in Chrome, I attempted to tweak some CSS in the elements panel and noticed the changes reflecting above in the DOM. However, when I navigate to the sources tab, I'm unable to modify ...

Online Platform: Transmit information from javascript on the client-side to python on the server-side

I recently completed building a website using HTML/CSS and JavaScript, which is currently being executed with a basic Python script. import http.server import socketserver PORT = 8000 Handler = http.server.SimpleHTTPRequestHandler with socketserver.TCPS ...

Notification box appearing on the homepage

I created a landing page featuring various products. Each product is accompanied by a description and price. When you click on a product, a "popup window" should appear displaying the picture and description. My concern is that if I have numerous product ...

Converting an array of objects into a dictionary using TypeScript

I'm attempting to convert an array of objects into a dictionary using TypeScript. Below is the code I have written: let data = [ {id: 1, country: 'Germany', population: 83623528}, {id: 2, country: 'Austria', population: 897555 ...

Error: A colon was unexpectedly encountered while trying to access the JSON API on tickets.com

I've been attempting to retrieve data from the following URL: http://api.master18.tiket.com/search/autocomplete/hotel?q=mah&token=90d2fad44172390b11527557e6250e50&secretkey=83e2f0484edbd2ad6fc9888c1e30ea44&output=json To do this, I am ut ...

Unable to receive Ajax POST requests in PHP

I've spent all day searching for a solution to my problem... I have an ajax post method that sends a variable value to a php page. The ajax post seems to be working fine as indicated by the success message, but I am unable to retrieve the value in php ...

Using Django's JSONField Nested within an ArrayField

I am encountering an issue when trying to insert data into a field using ArrayField with JSONField nested inside. models.py locations = ArrayField(JSONField(null=True, blank=True), blank=True, null=True) Insert location_arr = [{"locations": "loc1", "amou ...

Create a new tab without triggering the pop-up blocker by utilizing an iframe's JavaScript event

I currently have an iframe embedded in a webpage. Once data is successfully sent to the server within the iframe, the server responds with a new URL to be opened either in a new tab or the parent window. The main issue I am encountering is that the brows ...