When trying to sort an array of objects in JavaScript, the outcome can often be unpredictable

While attempting to organize an array of objects in descending order using pure javascript, I encountered a challenge. Initially, I suspected that the issue might be related to the JSON.stringify method, as discussed [here][1]. It turned out that JSON.stringify does not maintain the order of objects intentionally. When sorting the array of objects and then accessing the weight property of the first object in the array, I noticed that I would sometimes get a weight value of .29 or .35. Here is the code snippet I used:

var byWeight = objArray.slice(0);
var sorted = byWeight.sort(function(a,b) { return b.weight - a.weight; } );
sorted[0].something.weight;

Upon running this code multiple times, the weight value appeared to be randomly either .29 or .35. Can you explain why this inconsistency is happening?

Below is the array being processed:

[
  {
    "something": {
      "terms": [
        {
          "elements": {
            "number": {
              "span": [
                9,
                10
              ],
              "value": "1"
            }
          },
          "span": [
            9,
            12
          ],
          "value": "1g",
          "label": "grams"
        }
      ],
      "span": [
        9,
        12
      ],
      "weight": 0.29,
      "value": "1gm"
    }
  },
  {
    "something": {
      "terms": [
        {
          "elements": {
            "number": {
              "span": [
                16,
                18
              ],
              "value": "30"
            }
          },
          "span": [
            16,
            20
          ],
          "value": "30ml",
          "label": "liters"
        }
      ],
      "span": [
        16,
        20
      ],
      "weight": 0.35,
      "value": "30ml"
    }
  }
]

Answer №1

You are using the incorrect reference. Please modify this

var sorted = byWeight.sort(function(a,b) { return b.weight - a.weight; } );

to (observe .something.)

byWeight.sort(function (a, b) { return b.something.weight - a.something.weight; });

Example in action:

var data = [
  {
      "something": {
          "terms": {
              "span": [
              9,
              12
              ],
              "value": "1g",
              "label": "grams"
          }
      ,
          "span": [
          9,
          12
          ],
          "weight": 0.29,
          "value": "1gm"
      }
  },
  {
      "something": {
          "terms": {
              "span": [
              16,
              20
              ],
              "value": "30ml",
              "label": "liters"
          }
      ,
          "span": [
          16,
          20
          ],
          "weight": 0.35,
          "value": "30ml"
      }
  }
];

var sorted = data.slice(0);
sorted.sort(function (a, b) {
    return b.something.weight - a.something.weight; // descending order!
});
document.write('<pre>' + JSON.stringify(sorted, 0, 4) + '</pre>');

Answer №2

It seems like your objArray is not properly structured. The "terms" property should be an object instead of an array if it contains key-indexed elements like "span", "value", and "label". Additionally, your sorting logic is incorrect as it is currently looking at the wrong place; it should be referencing a.something.weight/b.something.weight. You can check out this example on jsfiddle for reference.

var objArray = [
  {
    "something": {
      "terms": {
          "span": [
            9,
            12
          ],
          "value": "1g",
          "label": "grams"
      },
      "span": [
        9,
        12
      ],
      "weight": 0.29,
      "value": "1gm"
    }
  },
  {
    "something": {
      "terms": {
          "span": [
            16,
            20
          ],
          "value": "30ml",
          "label": "liters"
      },
      "span": [
        16,
        20
      ],
      "weight": 0.35,
      "value": "30ml"
    }
  }
];
var byWeight = objArray.slice(0);
var sorted = byWeight.sort(function(a,b) { return a.something.weight - b.something.weight; } );
console.log(sorted[0].something.weight);

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

Using a dictionary to replace values in a Pandas DataFrame column with an array of new entries

I am working with a DataFrame that looks like this: tag1 other 0 a,c foo 1 b,c foo 2 d foo 3 a,a foo The entries in the DataFrame are strings separated by commas. In addition, I have a dictionary of definitions f ...

Even with e.preventDefault, the anchor link still opens in a new tab on the browser

I am dealing with an ajax call that triggers a REST API to return a list of all names, as well as another REST API that matches those names. For instance: /list returns: list1, list2, list3 and /api/list1.json returns: JSON data for list1.. Currently, ...

Having trouble displaying specific images on React Native, how can I resolve this issue?

I am currently developing a weather application that retrieves weather information and displays it using ForecastItem components. However, I have noticed that some of the components do not display the weather image randomly. On the Home screen, I use the ...

Guide to retrieving data from an Excel sheet column and populating it into an array

My situation involves an array structured as follows: myColumns = Array("Serial","Practice","Manager", "QTD") However, I am aiming to enhance its flexibility by retrieving values directly from a spreadsheet. (The values and their quantity can fluctuate) ...

JSON-generated Personalized Listview

I am facing an issue with displaying 2 pieces of data in one row of a ListView. The problem lies within the showList() method. I am unable to utilize my custom ListView XML to show both the item and itemsemail arrays, as it only displays one data. My goal ...

What is the best method to update a nested array value within MongoDB?

Is there a way to update a nested array value within another array value? Specifically, I want to set the status as enabled where alerts.id = 2. { "_id" : ObjectId("5496a8ed49847b6cd7c7b350"), "name" : "joe", "locations" : [ { ...

The onChange Event triggers only once in a checkbox input

I am implementing a checkbox component that emits an event to the parent component. However, in the parent component, I am facing an issue where I need to perform different actions based on whether the checkbox is checked or not, but it seems to only work ...

Is there a better way to combine JSON data in Python without using the eval() function

Imagine I have two JSON strings in a dictionary: JSONdict['context'] = '{"Context":"{context}","PID":"{PID}"}' JSONdict['RDFchildren'] = '{"results":[ {"object" : "info:fedora/book:fullbook"} ,{"object" : "info:fedo ...

The method of altering a menu link in WordPress using jQuery varies according to whether the user is logged in or not

I need to update the last link on my menu. When a user is logged in, it should display a profile link; otherwise, it should show a sign-up link. ...

Increase visibility, decrease visibility by utilizing ng-hide/ng-show and functions

As I implement the show more/show less feature, I am uncertain if achieving a smooth effect is feasible. However, I believe it's worth reaching out to this community for some creative ideas on how to make it possible. I have a list of dynamic links w ...

Guide on integrating jQuery list filtering in Ionic 2

I stumbled upon a jQuery function that filters data in HTML, found it online. Now, I want to incorporate a similar feature into my Ionic app. However, I am unsure about the modifications required in list-search-min.js. Here is a snippet of my index.html: ...

Shadowbox will only open on hover after being clicked once

I have been attempting to use Shadowbox to display images on hover, but I am experiencing an issue where it only works after I have clicked the link for the first time. This problem persists in both Chrome and FireFox. You can observe this behavior at: S ...

Tips for getting the setTimeout() function to behave like a for loop

Is there a way to achieve the setTimeout() function's behavior in a for-loop? Take a look at this code snippet: function hello() { for (let index = 0; index < 3; index++) { setTimeout(function () { console.log('What&bs ...

What is the reason that self focus doesn't function in JavaScript?

Whenever an input element triggers a blur event, I want to focus on a specific element. The issue arises when I try to focus on the same element that caused the blur event. Why does this only work when the element I am focusing on is not the one triggeri ...

Executing a function in AngularJS using PHP

My current project involves an Angular application that needs to load a PHP page within the view. The setup is functioning properly, but I now require an Angular function to run after the PHP code has loaded. I am wondering about the process of calling an ...

"Removing a row from a table using jQuery, JSON, AJAX, and PHP

My goal is to implement a feature that allows users to delete an entire row from a table. The process involves displaying the table first, and upon clicking the "delete" button in each respective row, a confirmation modal pops up prompting the user to conf ...

Guide to resolving a blank webpage issue post running 'npm run build'

I am currently in the process of working on a project that involves Vue and Firebase. Unfortunately, I have encountered an issue where my development server is no longer rendering new routes from my Vue router after building and deploying to production. F ...

What is the best method for creating a visual chart using information extracted from a JSON file?

I have a json file with various data entries and I'm looking to create a graph that displays the number of viewers for each user over different dates. I've been struggling with this all morning and could really use some assistance. Can anyone hel ...

A delivery person is sending a JSON post request with an empty body to the Express server

When I sent a POST request from Postman to the Express server, the body is getting parsed correctly using app.use(express.json()), but it returns an empty body. However, I am able to retrieve params and other information successfully. Strangely, it works ...

Discover the technique of accessing HTML/CSS toggle switch value in Golang

I am attempting to incorporate a toggle switch into my webpage. I followed this specific tutorial for guidance: w3schools.com Currently, I have set up my HTML file with a button and the toggle switch. Additionally, I configured my web server in Go to lis ...