Arranging a collection of objects (Displaying information in a random sequence)

Here is a summary of the data returned in a shortened version:

var array = 
[{
    "response":
        {
            "itineraries":[
            {
                "price":
                {
                    "totalPricePerPassenger":"104"
                }
            },
            {
                "price":
                {
                    "totalPricePerPassenger":"102"
                }
            },
            {
                "price":
                {
                    "totalPricePerPassenger":"103"
                }
            }
            ]
        }
}];

My intention is to organize the returned data based on total price.

Below is the code I'm using for sorting and displaying the outcome:

function sort(a, b){
    var a_price = a.response.itineraries.price.totalPricePerPassenger();
    var b_price = b.response.itineraries.price.totalPricePerPassenger(); 
    return ((a_price < b_price) ? -1 : ((a_price > b_price) ? 1 : 0));
}

var data = array.sort(sort); 
console.log(data);

The output from the console.log indicates that the prices remain in their original sequence without any changes.

Any thoughts on why this might be occurring? Am I heading in the right direction?

Answer №1

function sortByPrice(a, b){
    var a_price = a.price.totalPricePerPassenger;
    var b_price = b.price.totalPricePerPassenger; 
    return ((a_price < b_price) ? -1 : ((a_price > b_price) ? 1 : 0));
}

var sortedData = array[0].response.itineraries.sort(sortByPrice); 
console.log(sortedData);

You were sorting the outer array, not the inner array. By using this function, you are now correctly sorting the inner array based on price. Another option is to pass 'array' directly to the sort method since it sorts the array in place.

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

Altering styles of a child component within a parent component using material-ui

I am trying to customize the appearance of a child component from within the parent component Let's take a look at the child component, MyButton.js: import ButtonComponent from '@material-ui/core/Button' const useStyles = makeStyle((theme) ...

Struggling to generate a div using my JS/jQuery code

Currently working on a post-it web application to improve my skills in JavaScript and jQuery. I've encountered a few errors that have me stumped. Although I'm new to StackOverflow, I often use it as a helpful resource. You can find the code here ...

AngularJS does not recognize the service being referenced

I keep encountering an error in AngularJS saying that the service is not defined, even though my controller and module are properly connected: application.js: var myapp=angular.module('myApp', []); myapp.service('productService', fun ...

Running cy.task after all test suites can be done by adding the task in a

I need some guidance on running cy.task after executing all test suites. I have a file generated at the start of the tests that I would like to remove once they are completed. Regardless of whether any tests passed or failed, I want to trigger cy.task im ...

Making changes to a database model (updating or replacing)

When making changes to a model in the database, is it more efficient to only update a specific field or replace all objects at the same level with that field? ...

Issues have been encountered with Angular 5 when trying to make required form fields work properly

Just created my first Angular app using Angular 5! Currently following the documentation at: https://angular.io/guide/form-validation. Below is the form I have set up: <form class="form-container"> <mat-form-field> <input matInput pl ...

What is the best way to implement this design using CSS or JavaScript?

I would like to enhance the appearance of my school website during these challenging times of the pandemic by adding some CSS or JavaScript elements. However, I am unsure how to go about it. ...

Dominant Editing through ASP.Net Roles

Looking for guidance on how to effectively use knockout with asp.net membership roles in MVC 4. My goal is to incorporate an editable grid on the page based on whether the user is an administrator or a 'registered user'. I want to ensure that use ...

The Express Validator is unable to send headers to the client once they have already been processed

I recently integrated express-validator in my Express JS project, but encountered a warning when sending invalid fields to my api: UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client This ...

Is it possible to conceal the dates from past months in the datepicker plugin?

Currently, I am utilizing a datepicker tool from jQuery UI and adjusting its CSS to suit my requirements. My goal now is to hide any dates that are not currently active, specifically those displayed from other months. I am unsure if this can be achieved ...

Is there a method to retrieve all Class elements without using a for-loop?

I am trying to retrieve all elements with a specific class using document.getElementsByClassName(); <body> <div class="circle" id="red"></div> <div class="circle" id="blue"></div> <div class="circle" id="yell ...

Establishing a connection between a Google spreadsheet to create and automatically update calendar events

I'm currently working on connecting my Google Sheet to a calendar so that it can automatically generate calendar events and keep them updated based on changes made in the sheet. The Google Sheet I'm using tracks new building opening dates and con ...

Creating a student information database through an array of structures in the C programming language

The function calculateGrade() is designed to generate a database of up to 50 students utilizing an array of structures. This function requires inputting the student's name, test score, and exam score in order to compute the total score and display it. ...

Vertical scroll bar positioned on the left side of a DIV

Can a vertical scroll bar be placed on the left side of a DIV using CSS? What about JavaScript? ...

Encountering an issue while trying to launch an Angular application on localhost. Vendor.js resource failed to load

Whenever I compile the code, it runs successfully. However, when I try to serve the application using 'node --max-old-space-size=8192', even though it compiles without any errors, when I open the app in a browser, it returns an error saying "Cann ...

What is the best way to trigger the Vue.js ApolloClient middleware to run again?

Within my main.js, I have implemented a code snippet that checks if a certain item exists in the localStorage. If it does, the code will add an Authorization header to the ApolloClient setup using middleware. However, if a new item is added to the localSt ...

Switch content based on value with Javascript

One of my elements is: <a href="#" type="link" class="button send" classAct="button send" classSel="button send pressed" label="encrypt" title="sendmessage" onclick="add_encryption();">Encrypt</a> When toggled via the JavaScript below, I want ...

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 ...

The function does not yield any result

import { Injectable } from '@angular/core'; export class Test { public id: number; public name: string; public fid: number }; export const TESTS2: Test[] = [ {id: 1, name: 'Lion', fid: 1}, {id: 2, name: 'Tiger', fid: 1 ...

It ceases to function when transferred to another file

I have a function written in coffeescript that goes like this: _skip_version = (currentVersion, skippedVersions) -> if (currentVersion.indexOf(skippedVersions) == -1) return false return true This function is currently located in my archive.sp ...