The JSON sorting functionality seems to be functioning improperly

Here is a sample of my JSON data:

[
  {
    "cash": 100,
    "uid": "LHy2qRGaf3nkWQgU4axO",
    "name": "test2"
  },
  {
    "cash": 1000000,
    "uid": "01wFhCSlnd9vSDY4NIkx",
    "name": "test"
  },
  {
    "cash": 500,
    "uid": "PBOhla0jPwI4PIeNmmPg",
    "name": "test3"
  }
]

I am attempting to sort the JSON objects by the user's cash amount. Here is the code snippet I used:

    var objArr = []; // array containing JSON objects

    function compare(a, b) {
        console.log("a" + a.cash);
        console.log("b" + b.cash);
        if (a.cash > b.cash)
            return -1;
        if (a.cash < b.cash)
            return 1;
        return 0;
    }

   var obj = objArr.sort(compare);
   response.send(obj);

However, the response returned is not ordered as expected. Can anyone help me understand how to correct this issue? Thank you.

Answer №1

Here are a couple of important points to consider:

  1. Your code currently sorts in descending order rather than being unordered.

  2. In your code, you are utilizing the return value of the sort function. Keep in mind that this can give the incorrect impression that the returned array is a different array from the original. In reality, it is the same array, so it's generally advisable not to rely on the return value.

  3. A shorter version of your sorting logic could be achieved with:

    // For ascending order:
    return a.cash - b.cash;
    
    // For descending order:
    return b.cash - a.cash;
    

Support for Point #1 above:

var objArr = [
  {
    "cash": 100,
    "uid": "LHy2qRGaf3nkWQgU4axO",
    "name": "test2"
  },
  {
    "cash": 1000000,
    "uid": "01wFhCSlnd9vSDY4NIkx",
    "name": "test"
  },
  {
    "cash": 500,
    "uid": "PBOhla0jPwI4PIeNmmPg",
    "name": "test3"
  }
];

function compare(a, b) {
  console.log("a" + a.cash);
  console.log("b" + b.cash);
  if (a.cash > b.cash)
    return -1;
  if (a.cash < b.cash)
    return 1;
  return 0;
}

var obj = objArr.sort(compare);
console.log(obj);
.as-console-wrapper {
  max-height: 100% !important;
}

Demonstration of Points #2 and #3:

var objArr = [
  {
    "cash": 100,
    "uid": "LHy2qRGaf3nkWQgU4axO",
    "name": "test2"
  },
  {
    "cash": 1000000,
    "uid": "01wFhCSlnd9vSDY4NIkx",
    "name": "test"
  },
  {
    "cash": 500,
    "uid": "PBOhla0jPwI4PIeNmmPg",
    "name": "test3"
  }
];

console.log("ascending", objArr.sort((a, b) => a.cash - b.cash));
console.log("descending", objArr.sort((a, b) => b.cash - a.cash))
.as-console-wrapper {
  max-height: 100% !important;
}

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

JavaScript's Selenium WebDriver - Explicit Waiting

Currently, I am utilizing selenium-webdriverjs. My objective is to pause until a specific element is displayed. To accomplish this, I have implemented an explicit wait that operates effectively: var shown = false; driver.wait(function(){ driver.findEl ...

When using Next.js and Express.js together, CORS error may occur, causing API queries to only function properly during build

I am currently working on a project that involves using Next.js for the front-end and Express.js for the back-end. Front-end Setup The 'pages' directory contains an 'index.js' file where I have implemented the following code snippet: ...

Unveiling the method to fetch the emitted value from a child component and incorporate it into the parent component's return data in Vue

How can I retrieve the title value passed by the Topbar component and incorporate it into the data() return section? I attempted to create a method to pass the value, but was unsuccessful despite being able to successfully log the value in the parent file. ...

Is your data coming in as NaN?

I am currently developing a basic webpage that has the capability to calculate your stake and determine your return, reminiscent of a traditional betting shop. As of now, I have successfully hard coded the odds into my page. However, while testing my code ...

What is the prescribed interface or datatype for symbol type in TypeScript with JavaScript?

I have a set of symbol values in JavaScript that I want to convert to TypeScript. // Defining object values in JavaScript const size = { Large: Symbol('large'), Medium: Symbol('medium') } What is the most efficient method to conv ...

Implementing bbcode feature in TinyMCE

Take a look at the custom html code provided below: <button type="button" class="btn btn-default btn-sm" onclick="appendBBCode('youtube','ContentArea')">[youtube]</button> <br> <div class="form-group field-boats-co ...

We could not locate the requested resource with a DELETE request using the fetch JSON method

Currently, I am in the process of developing a webpage that utilizes JSON API REST alongside XAMPP with an Apache server. Up until now, everything has been working smoothly as I have been utilizing the DELETE method successfully. However, I seem to have hi ...

Leveraging the content delivery network for react-select in a react.js project

I'm having trouble using react-select with cdn. I attempted to download the cdn for react-select but keep encountering an error stating that 'select is not defined'. I also tried downloading the zip package for react-select, but I am unsure ...

Sharing data across multiple paths

route.post('/register',function(req,res){ //completed registration process // token value assigned as 'abc' }) route.post('/verify',function(req,res){ // How can I retrieve the token ('abc') here? }) I' ...

Converting image data from JSON to SQLite in Android development

As a beginner in Android Programming, I have successfully parsed JSON text and stored it in sqlite. The data is displayed in a listview within my app, but I haven't yet figured out how to parse the images included in the JSON file. After browsing thro ...

Production environment does not support Meteor environment variables

I am currently deploying my app using Meteor UP and I have set the environment variables in both the mup.json file and a file called server/lib/env.js where they are stored. Here is how the variables are being accessed: Meteor.startup(function() { // ...

Retrieve information from a .json file using the fetch API

I have created an external JSON and I am trying to retrieve data from it. The GET request on the JSON is functioning correctly, as I have tested it using Postman. Here is my code: import "./Feedback.css"; import { useState, useEffect } from " ...

Phone Validation for Contact Form 7

Recently, I was tasked with creating a landing page for a job interview. The challenge was to include validation on the phone number field so that it has to be between 9 and 10 numbers in length, along with another validation requiring the phone number t ...

"Performing validation on a number input by using the ng-change event

Im using a number input that dynamically sets the min and max values based on another form field. I have two scenarios: Level 1: Min = 2, Max = 50 Level 2: Min = 5, Max = 1000 I've set up an ng-change event on the input field to check if the entere ...

"Delivering dynamic HTML content using React/Redux variables in the production environment

I am currently in the process of developing a React web application, and I have encountered an issue where a variable intended to store a schedule is being filled with the HTML content of the page when I build and serve the application. Interestingly, the ...

Why does socket.io have trouble connecting when clients are using different IP addresses on separate wifi networks?

I've encountered an issue where socket.io won't connect when clients are on different wifi networks (ip address) using my self-configured Ubuntu Nginx server. Strangely enough, it works perfectly fine on a pre-configured Heroku server. Here is a ...

Concealing the rear navigation button within the material carousel

I have a material css carousel, and I am trying to hide the back button on the first slide. I attempted to use the code below from a previous post The following code snippet prevents the user from looping through the carousel indefinitely. Stop looping i ...

Having trouble with the Document.createElement function not functioning properly when trying to download a

ISSUE While my PDF download feature functions properly in Chrome, it encounters difficulty when attempting to work in IE 11/10/9. When using IE, I receive a security warning prompt. After selecting Yes to allow the download, nothing happens. SOURCE CODE ...

Use CSS media queries to swap out the map for an embedded image

Looking to make a change on my index page - swapping out a long Google Map for an embedded image version on mobile. The map displays fine on desktop, but on mobile it's too lengthy and makes scrolling difficult. I already adjusted the JS setting to "s ...

Automatically Trigger Knex.JS Updates

Utilizing the migration tools provided by Knex.JS, I am attempting to create a table with an automatically updating column named updated_at whenever a record is modified in the database. Take, for instance, this table: knex.schema.createTable('table ...