Arranging an array of JavaScript objects based on a sub-array's property/value

When data is returned from a server, the structure may not always be in our control. For example...

var data = {
    "TrackingResults": [
        {
            "Name": "Pack One",
            "Products": {
                "Product": [
                    {
                        "ProductName": "Soccer Ball"
                    },
                    {
                        "ProductName": "Tennis Racket"
                    },
                    {
                        "ProductName": "Gold Putter"
                    }
                ]
            },
            "status": "Despatched",
            "Location": "Alabama",
            "Type": "Parcel"
        },
        {
            "Name": "Pack Two",
            "Products": {
                "Product": [
                    {
                        "ProductName": "Backet Ball Hoop"
                    },
                    {
                        "ProductName": "Base Ball Glove"
                    }
                ]
            },
            "status": "Despatched",
            "Location": "Florida",
            "Type": "Parcel"
        }
    ]
};

In this scenario, we need to sort each Tracking Result by the first Product Name but struggle to find code that can handle sorting based on a sub-array property or value.

Answer №1

To achieve proper sorting of an array, it is recommended to utilize the Array.sort method along with a customized comparator function:

const customSort = function (item1, item2) {
    let name1 = item1.Items.Item[0].Name;
    let name2 = item2.Items.Item[0].Name;
    return name1.localeCompare(name2);
}

This approach ensures that the elements are arranged based on the locale settings of the user's web browser. Simply provide the custom sort function as an argument to the sort method:

data.ProductsList.sort(customSort);

Answer №2

To properly organize it, you should manually input it in this format: (using the clue on localeCompare from johnsmith's suggestion)

var result = data.OrdersList.sort(function(a,b){
    return a.Products.Product[0].Name.localeCompare(b.Products.Product[0].Name)
});

This method is effective for arranging OrdersList items.

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

Converting Newtonsoft JSON to string when the language on the device is not set to English

My challenge revolves around parsing a JSON block within my Monodroid application: bubbles {{ "count": 4, "lat": 42.78875, "lng": -90.255, "bubble_icon": "m1.png" }} The code I am currently using is as follows: string s= bubbles ["lat"].ToSt ...

Why does the process of joining and replacing elements in a character array using the JavaScript functions stop when it reaches the "<" character?

In my code, I am utilizing the JavaScript function join("") to convert a character array into a string while removing comma separators between characters. Typically, this method works flawlessly, but recently I encountered an issue when there is a "less th ...

Unable to deploy Firebase functions following the addition of an NPM package

Scenario: I recently tried integrating Taiko into my Firebase web application, similar to Puppeteer. It's worth mentioning that Taiko downloads Chromium for its operations. Challenge: Ever since then, none of my functions are deploying successfully. ...

Altering the DOM directly within the componentDidMount() lifecycle method without needing to use

In ReactJS, I am facing an issue while trying to manipulate the DOM in the componentDidMount() method. The problem lies in the fact that the DOM is not fully rendered at this point, requiring me to use a setTimeout function, which I find undesirable. Upon ...

Having trouble updating the state value using useState in React with Material-UI

I have developed a unique custom dialog component using Material-UI const CustomDialog = (props) => { const [dialogOpenState, setOpen] = React.useState(props.dilaogOpenProp); return ( <> <CssBaseline /> <Dialog ...

One way to change the cursor CSS property is by dynamically altering it based on scrolling behavior. This involves modifying the cursor property when scrolling

I'm attempting to adjust the cursor property within an Angular function. The issue I'm facing is that when I begin scrolling the webpage, the cursor changes to a pointer, but when I stop scrolling, it remains as a pointer. I've attempted to ...

Storing files offline in Firefox 3.5 with file:// protocol

While experimenting with the code for offline storage in Firefox 3.5, I referred to a tutorial on . When the page loads, I am prompted with a dialog asking to store data, but after clicking Allow, the dialog does not disappear. The application functions co ...

Exploring the process of sending props via the render method in Vue.js and observing their behavior

Struggling with passing a prop from a parent component down to a child created using CreateElement/render in vue.js and then watching it. Here is the parent component: Vue.component('my-drawing', MyDrawing) new Vue({ el: '#drawing' ...

Managing fresh data entries in meteorology

In my current setup, I have a "requests" collection and I have successfully set up publications on the server side and subscriptions on the client side. My question is, how can I effectively handle new records in MongoDB? Specifically, I would like to re ...

Retrieving the day, month, and year from a date/timestamp within an array using MongoDB aggregation technique

This method is used to identify any object "gt" with a date, or between two dates using "lt". Here is how it's done: db.compte.aggregate([ { $project: { time: { $filter: { input: "$auditMessages", as: "auditMes ...

Steps to insert a personalized attribute into a TypeScript interface

UPDATED EXPLANATION: I'm fairly new to TypeScript, so please bear with me if this question seems basic. I'm working with an existing library (ngx-logger) that I don't want to or can't modify. My goal is to create a service that generat ...

Understanding the correct Accept Content-Type selection in ExpressJS

I'm struggling to differentiate an AJAX call from other calls in ExpressJS. From what I gather, can I use request.accepts('json') to recognize a JSON request? The issue is - it seems like every call accepts everything! app.get( '*&ap ...

Inconsistencies in JavaScript comparison across various web browsers

Here is a snippet from my JavaScript code var dataList = eval(strArray[0]); for (i = 0; i < dataList.length; i++) { console.log(((dataList[i].isFollowed == 0) ? "Follow" : "Unfollow")); } However, this code exhibits varying behavio ...

Drop delete method not functioning as expected

Currently, I am trying to work on a JavaScript delete function that is supposed to delete a row from an SQL table. However, it seems like the function is not working properly. Let me share the code with you: $(document).ready(function(){ $( "#draggabl ...

Retrieving XML using JavaScript with AJAX

Having trouble retrieving XML data using JavaScript and Ajax. The script takes too long (up to 45 seconds) to collect the data from the database and return it as XML. Everything works fine when loading the data locally, so no issues with cross-domain. An ...

BigQuery Request Body

Hello there, Currently, I am conducting a test on a post method within another system that utilizes BigQuery as its data source. In this test, I am specifically looking into the call method on live data from BigQuery to assess how the API request receives ...

"Enhance your web development skills by mastering jQuery alongside the

It's curious that jQuery doesn't support the use of the "+" sign. You can see how it functions with "1" and "3", but not with "2+". Just hover your mouse over each div to experience it. <div id="div-2+"></div> JSFiddle $('a. ...

Creating an array of JSX elements or HTMLElements in a React TypeScript rendering

Currently in the process of developing a custom bootstrap card wrapper that allows for dynamic rendering of elements on the front and back of the card based on requirements. Here is the initial implementation: import React, { useState, ReactElement } from ...

Utilizing AngularJS 1.X to implement filters on transformed information

When using the combination of ng-repeat and a filter, it creates a highly effective search function. However, once the data is converted, the use of a filter for searching becomes limited. For Instance JavaScript $scope.ints = [0,1,2,4,5,6,7,8,9, ..., 9 ...

Set up a global configuration for all $.ajax calls to enable automatic retries in case of a timeout

Looking for a solution to implement a global timeout function using $.ajaxSetup in my Phonegap app. The goal is to automatically retry ajax GET or POST requests in case of timeout, specifically due to poor internet connection. As a Backbone.js user, I hav ...