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

Set maximum size for background image in div

I'm facing some challenges with setting the maximum height of a background image within a div. I want the max height to be equal to the actual height of the image, without stretching it. Ideally, if there is excess content in the div, it should stop a ...

Javascript Solution for Testing Palindromes in a Linked List

I recently researched the solution for a palindrome problem using Javascript. There is one particular line of code that I am struggling to comprehend, and I'm hoping someone can shed some light on it for me. Here is the code snippet in question: thi ...

Vue.js: Awaiting Firebase to finish loading

I'm facing an issue with integrating Firebase into a Vue JS component. It seems like the firebase object loads after my component is created. Is there a way to ensure that Firebase is fully loaded before running any JavaScript code? For example, I w ...

Efficient method of delivering cohesive information from database to user without the need for continuous querying

Within the database, there is stored data about each user that typically remains constant. However, occasionally a user may update their information, such as changing their name. This data includes the user's name, username, and company details. The ...

Guide to sending a similar request as a curl command through a JavaScript file

After reviewing this Stack Overflow post titled "JavaScript post request like a form submit", I came across a similar situation. Currently, I have a curl command that performs as expected: curl -v -X POST -H "application/json" -H "Content-type: applicatio ...

Is it possible to extract tooltip text from a website using Python and Selenium, specifically when the text is generated by JavaScript?

Can anyone help me retrieve the tooltip text that appears when I hover over the time indicating how long ago a game was played? You can find my summoner profile here. I have noticed that the tooltip text is not visible in the HTML code and suspect it may ...

Get started with adding a Typescript callback function to the Facebook Login Button

I am in the process of implementing Facebook login into my Angular7 application using Typescript. Although I have successfully integrated Facebook's Login Button plugin for logging in, I am facing issues with providing a callback method to the button& ...

Creating an interface that accurately infers the correct type based on the context

I have an example below of what I aim to achieve. My goal is to start with an empty list of DbTransactInput and then add objects to the array. I experimented with mapped types to ensure that the "Items" in the "Put" property infer the correct data type, w ...

Display or conceal fields depending on custom object specifications

I am attempting to centralize my show/hide functionality for fields in one object (like vm.foo) that contains key-value pairs. For example, I could add another pair like 1502: true to hide a field with the key 1502. Is there a way to pass variables from t ...

I possess a JSON array object and need to identify and extract the array objects that contain a specific child node

const jsonArray = { "squadName": "Super hero squad", "homeTown": "Metro City", "formed": 2016, "secretBase": "Super tower", "active": true, "members": [ { "name": "Molecule Man", "age": 29, "secretIdent ...

Implementing Angular 4 to fetch information from a JSON file

As a beginner in Angular, my current task involves loading data from a JSON file upon click, which I have successfully achieved so far. However, I am facing an issue where I'm unable to load the first JSON object before clicking, meaning that I want ...

Ways to integrate npm dependencies into your Cordova plugin

Currently working on implementing a Cordova plugin called core-cordova found in this repository. This particular plugin has a dependency on another NPM package. The issue arises after installing the plugin in my app using: $ cordova plugin add @aerogears ...

Tips for resolving issues related to Nodemailer configuration

I am currently working on a script that sends form data to an email address. I am using Express and Nodemailer with Node.js, but as a beginner, I am struggling to understand why the email authorization stops and prevents the letters from being sent. Here ...

Taking data input from three textboxes and storing them in a PHP array

In my HTML form, I have 3 text input fields and one submit button. Each text field is intended for entering the name of an animal, which should then be saved into a PHP array. Here is the structure of my HTML form: <form action="Test.php" method="post ...

Troubleshooting: Issue with passing parameters in Wordpress ajax function

In my Wordpress Ajax implementation, I am facing an issue where the parameter value metakey: id is not being passed to $_POST["metakey"]. As a result, when I do a var_dump($_POST), it shows array(0) { }. If I manually set a static value for the variable i ...

Troubleshooting the Ng2-Charts Linechart to display all values instead of just the first two

Starting a new Angular application with the Angular-CLI (beta 22.1) has presented an issue when adding test data (5 values) to a chart. The scaling appears incorrect, displaying only the first two values stretched across the entire length of the graph (ref ...

displaying information in table cells with jquery

Is there a way to display a table inside a td element with an on-click function without showing all tables in the same column when the function is triggered? I want the table to be shown only for the specific td that was clicked. $(document).ready(funct ...

Sending a parameter to a request-promise function within an iteration through a forEach loop

I have successfully implemented an API call for price data. However, I am facing an issue while trying to pass the variable exchange_pair_id into the then() function. Within the forEach loop, the exchange_pair_id is accurate for each asset. But inside the ...

Is the max and min-width being properly set by the keen-slider__slide class in keen-slider?

Check out my code snippet below: import React from 'react' import { useKeenSlider } from 'keen-slider/react' // Styles import 'keen-slider/keen-slider.min.css' interface Props { children: any } // const animation = { du ...

What is the best way to incorporate JavaScript code as React syntax?

For my project, I am using the OpenLayers API Map. I'm unsure of the correct way to incorporate JavaScript code in React or vice versa. Here is an answer on how to use markers in the map, but I am struggling to implement it in my current code since I ...