Arranging elements in two arrays in either ascending or descending order

Looking to implement sorting functionality for the "fuel.name" value within this array...

const orders = [  
  {  
    "_id":"5d14a31490fb1e0012a3d2d8-1",
    "orderId":"0JL5ORM0JT-1",
    "created":"2019-06-27T11:05:56.377Z",
    "createdDate":"2019-06-27T09:05:56.377Z",
    "offers":[  
       {  
          "price":95.27,
          "fuel":{  
             "_id":"5ce13948eaef5200113b0de8",
             "name":"Diesel B7",
             "description":"Diesel",
             "lpt":0,
             "duty":0,
             "type":"SPOT",
             "created":"2019-05-19T11:08:56.417Z"
            }
         },
         {
           "price": 95.27,
           "fuel": {
             "_id": "5ce13948eaef5200113b0de8",
             "name": "Petrol",
             "description": "Petrol",
             "lpt": 0,
             "duty": 0,
             "type": "SPOT",
             "created": "2019-05-19T11:08:56.417Z"
           }
         },
         {
           "price": 95.27,
           "fuel": {
             "_id": "5ce13948eaef5200113b0de8",
             "name": "Fossil Fuel",
             "description": "Fossil Fuel",
             "lpt": 0,
             "duty": 0,
             "type": "SPOT",
             "created": "2019-05-19T11:08:56.417Z"
           },
         }
      ]
   }
]

The goal is to rearrange the "offers" objects based on the "fuel.name"

orders.sort((a: any, b: any) => a.offers[0].fuel.name.toUpperCase().localCompare(b.offers[0].fuel.name))

After console logging the above code, it's not returning the desired order. To replicate the issue, you can check out this fiddle.

Answer №1

You are currently organizing the orders array by the first element in each offers array. It would be more efficient to sort the offers array within each object in the orders array.

const orders=[{_id:"5d14a31490fb1e0012a3d2d8-1",orderId:"0JL5ORM0JT-1",created:"2019-06-27T11:05:56.377Z",createdDate:"2019-06-27T09:05:56.377Z",offers:[{price:95.27,fuel:{_id:"5ce13948eaef5200113b0de8",name:"Diesel B7",description:"Diesel",lpt:0,duty:0,type:"SPOT",created:"2019-05-19T11:08:56.417Z"}},{price:95.27,fuel:{_id:"5ce13948eaef5200113b0de8",name:"Petrol",description:"Petrol",lpt:0,duty:0,type:"SPOT",created:"2019-05-19T11:08:56.417Z"}},{price:95.27,fuel:{_id:"5ce13948eaef5200113b0de8",name:"Fossil Fuel",description:"Fossil Fuel",lpt:0,duty:0,type:"SPOT",created:"2019-05-19T11:08:56.417Z"},}]}];

orders.forEach(o => 
    o.offers.sort((a, b) => a.fuel.name.localeCompare(b.fuel.name))
);
    
console.log(orders)

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

Determine the quantity of elements within a JSON object based on specified criteria

I am seeking a way to count the number of items in an array of JSON objects that meet specific conditions. The structure of my array is as follows: array = [{ name: 'Bob', age: 24 }, ...., { ...

Easily move elements using a jQuery click animation

Having trouble animating a div's top position by -130px to move it off screen? Can't figure out why it's not working? I'm fairly new to jQuery/Javascript. I have a button/hyperlink with the ID #NavShrink. When clicked, I want the div # ...

Utilizing the push method to add a JavaScript object to an array may not be effective in specific scenarios

When I tried using users.push within the 'db.each' function in the code below, it didn't work. However, moving the 'users.push' outside of it seemed to do the trick. Is there a way to successfully push the new objects from db.each ...

Is there a way to determine if the browser window is currently in use?

The code I am currently working with looks like this: let focus; function setFocus() { focus = true; } function hideWindow() { focus = false; } window.onfocus = setFocus(); window.onblur = hideWindow(); The intention behind this code is to use it in the ...

Troubleshooting HMR issue in webpack 4 for ReactJS: HTML and SCSS not refreshing

Currently, I am setting up webpack for my application and in development mode, I would like to enable HMR (Hot Module Replacement) that automatically refreshes the page whenever there are changes in HTML, SCSS, and JSX files. The entry point for my project ...

Alexa Skills Issue: Problem with Playing AudioPlayer HLS Stream URL

I'm currently using the "AudioPlayer" feature from the "Alexa Skill Kit" to stream an HLS audio format URL. No errors are showing up from AWS Lambda or the Developer Portal. I've been testing it with Silent Echo (). Alexa can play MP3 URLs and so ...

Encountering a "DOM Exception 11: InvalidStateError" when attempting to use websocket.send

I encountered the following error message: DOM Invalidate exception 11 This error is coming from the code snippet below, but I'm having trouble identifying the root cause. /*The coding style may appear pseudo-stylish with potential syntax errors*/ ...

Attaching to directive parameters

I've been working on creating a draggable div with the ability to bind its location for further use. I'm aiming to have multiple draggable elements on the page. Currently, I've implemented a 'dragable' attribute directive that allo ...

Unique button for custom "CODE" in Froala

Looking to create a custom button with functionality similar to bold (B) but for source code (Src). I have attempted the following, however it is not fully functional: $("#elm1").editable({ inlineMode: false, minHeight: 300, buttons: ["src"], c ...

What distinguishes submitting a form from within the form versus outside of it?

When the code below, you will see that when you click btnInner, it will alert 'submit', but clicking btnOuter does not trigger an alert. However, if you then click btnInner again, it will alert twice. Now, if you refresh the page: If you first ...

Interactive PayPal quick checkout feature

Currently, I am in the process of developing an online store for a personal project and this piece of code is extracted from my application. <div class="row"> <script src="https://www.paypalobjects.com/api/checkout.js"></script> {{#e ...

Trouble with scrolling on Kendo chart while using mobile device

I am facing an issue with multiple kendo charts on my website. These charts have panning and zooming enabled, but in the mobile view, they take up 100% of the width which causes touch events to not work properly for scrolling. I attempted to attach an even ...

invoking a function by utilizing nested controllers

Struggling with nested controllers, the main goal of this code is to link data extracted from a .json file to another function or file. .html file: <div ng-app="myApp" ng-controller="GetCtrl" > <li ng-controller="ChannelCtrl" ng-repeat="x in ...

A guide on conditionally rendering components in React

When I try to add a nested if statement in JSX, condition ? true example : false example works perfectly. However, when I change it to if(condition) { ... }, it displays an error in the console: https://i.stack.imgur.com/TIBRo.jpg Example with one-line c ...

Tips for fading the text of list items when their checkbox is marked as done?

I am trying to figure out how to gray out a list item when its checkbox is checked. The code I currently have takes text input from a textbox and adds it to an unordered list when the add button is clicked. Each list item contains a checkbox within it. My ...

Customizing Tabs in Material UI v5 - Give your Tabs a unique look

I am attempting to customize the MuiTabs style by targeting the flexContainer element (.MuiTabs-flexContainer). Could someone please clarify the significance of these ".css-heg063" prefixes in front of the selector? I never noticed them before upgrading my ...

Utilize dynamic function calls in JavaScript

I am trying to dynamically call a function from a string like "User.find". The goal is to call the find() function in the User object if it exists. This is what my attempt looks like: var User = {}; User.find = function(){ return 1; } var input ...

Deleting information from several stores in React Reflux using a single action function

In the AuthActions file, there is a straightforward function called _clear that assigns this.data to undefined. This function is only invoked when a user logs out. However, upon logging back in with a different user, remnants of data from the previous ac ...

SystemJS could not locate the root directory for RxJS

There seems to be an issue with SystemJS loading rxjs modules on Windows, as it throws a 404 Not Found error on the rxjs directory. This problem does not occur on OSX, and all modules are up to date. GET http://localhost:8080/node_modules/rxjs/ 404 (Not F ...

What is the best way to trigger a function after the v-model has been updated

When attempting to filter an array of objects in Vue using input, I encountered issues with Salvattore not functioning correctly for building a grid of the filtered elements. It seems that calling the rescanMediaQueries() function after changes to my v-mod ...