What is the best way to alphabetically sort a nested array without changing the sequence of the surrounding array of elements?

I am dealing with an array of objects known as "Inventory". In each inventory object, there is an order property that I need to sort in ascending numerical order. Each inventory object also contains an array of vehicles, and within this array lies a model property which is another array.

    inventory: [
     {
       category: American,
       order: 1,
       vehicles: [
        {
          instock: 'yes',
          model: [
             {
               lang: 'en-US'
               title: 'mustang'
             }
          ]
        }
     ],
     [
        {
          instock: 'no',
          model: [
             {
               lang: 'en-US'
               title: 'viper'
             }
          ]
        }
     ],
     [
        {
          instock: 'yes',
          model: [
             {
               lang: 'en-US'
               title: 'camaro'
             }
          ]
        }
     ]


    }
   ]

My goal is to create a method that will maintain the sorting of the inventory array based on the 'order' property while also sorting the 'vehicles' array alphabetically by the 'title' property within the model array.

I have attempted a method that successfully sorts the order of the 'inventory' objects, but I am unsure if I can incorporate an additional sorting method to arrange the vehicles array accordingly.

 const sortedInventory = inventory.sort((a, b) => {
        if (a.order < b.order) return -1;
        if (a.order > b.order) return 1;
        return 0;
      })

Answer №1

To organize your inventory list by sorting vehicles within each inventory without changing the original order of the inventories;

Update Answer modified based on OP's feedback.

for (const inv of inventory) {
     inv.vehicles.sort((a, b) => { 
             if (a.model[0].title < b.model[0].title) return 1;
             if (a.model[0].title > b.model[0].title) return -1;
             return 0;
         });
}

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

Implementing Ng-debounce selectively for functions within an AngularJS application

I am looking to execute specific functions at different time intervals when there is a change in input. The current setup is as follows: <input type="text" name="title" ng-model="title" placeholder="Search..." ng-model-options="{ updateOn: 'defaul ...

Encountering a User Agent error while trying to update Vue to the latest version using N

I was interested in experimenting with staging.vuejs. When I tried to install it using the command npm init vue@latest, I encountered an error. Here is the link for reference: https://i.stack.imgur.com/rCipP.png SPEC Node : v12.13.0 @vue/cli : v4.5.15 ...

Do multi-dimensional arrays automatically contain null values when they are defined implicitly?

One situation I'm facing is having: public static BlockQuadrant[] EditModeBlocks = new BlockQuadrant[9]; However, when attempting to use them, a null value exception occurs. Surprisingly, all the values are null. Initially, I believed this was due t ...

Step by step guide on inserting View and Delete buttons in an HTML table populated by JSON data

I've successfully loaded data from a JavaScript file in JSON format into a plain HTML table using JavaScript. Everything is working well so far. I now want to enhance the table by adding two buttons, View and Delete, that when clicked will redirect to ...

Having Trouble with Imported JavaScript File in Astro

Why isn't the js file working in Astro when I try to import or add a source in the Astro file? For example: <script src="../scripts/local.js"></script> or <script>import '../scripts/local.js'</script> I am ...

What is the best way to correctly render several React components using a single index.js file?

I am facing an issue with rendering two React component classes. One class creates a counter and works fine, while the other class generates a simple string wrapped in HTML tags but does not render. I have tried various tutorials to troubleshoot this probl ...

Unpredictable Redirection when URL is Clicked using PHP or Javascript

Looking to send users to a random URL from a specific list? For instance: With 3 URLs available - Google.com, Facebook.com, and Yahoo.com <a href="<?php $sites[array_rand($sites)] ?>">Click here</a> Upon clicking the link, users will ...

Set Sprite Canvas Material to match the color of a different element

Can someone please guide me on changing the color of the Sprite Canvas Material? var material = new THREE.SpriteCanvasMaterial( { color: 0xffffff, I am trying to make it match the color of another element based on a specific ID or class. However, I' ...

Showing Data from JSON on an HTML Page

My project in play framework requires displaying Strings from a Json (containing a list of Strings) in a table on an html page. I attempted to use ajax and jquery for this purpose, but the implementation is not functioning correctly. Here is my javascript ...

Passing a callback function through a prop in Vue.js

Currently, I have a component structured in the following way: <template> <div> <pagination class="center" :pagination="pagination" :callback="loadData" :options="paginationOptions"></pagination> </div> </t ...

Navigating multi-level drop-down menus on touch devices can be tricky, but there are ways to effectively

I recently created a website using HTML and CSS with a three-level navigation menu that worked perfectly on desktop. However, the issue arises when users access the site from touch devices like smartphones or tablets because the sub-menu does not appear wh ...

update and rejuvenate session information using Node.js and express-session

Currently, I am working with Node.js in conjunction with express-session. Within my codebase, there is session data containing user information. req.session.user Upon updating the user's information, I update the session with the new data and then r ...

Tips for effectively incorporating customized validation into an array using vuelidate

My array of objects has a specific structure that looks like this varientSections: [ { type: "", values: [ { varientId: 0, individualValue: "" } ] } ] To ensure uniqueness, I implemented a c ...

JavaScript not properly rendering CSS styles

If I insert the following HTML statically, the CSS style is correctly applied. HTML: <li class="connector"> <a href="#"> <img src="css/images/temp/connector2.png" alt="" width="192" height="192"> <span class="sr-only"& ...

Ways to retrieve a value from a span using the Document Object Model

sample.html <span id='char'>{{value}}</span> sample.ts console.log((<HTMLInputElement>document.getElementById('char'))) This code snippet will display <span id='char'>ThisIsTheValueupdated</sp ...

What methods can be used to control access to document.styleSheets data, and what is the purpose behind doing so?

Recently, I came across the document.styleSheets API, which allows you to access stylesheets used by a website. Using this API is simple, for example, document.styleSheets[0].cssRules will provide all CSS rules for the first stylesheet on a page. When I t ...

Displaying an image based on user input

I'm attempting to display an image using JavaScript after a user completes an input field. I've managed to show the URL when using an input type="text," but when I attempt to change it to an img tag, it returns [object Object]. Is this achievable ...

Encountered Runtime Issue of TypeError: undefined cannot be iterated (unable to access property Symbol(Symbol.iterator))

I've been working on a multiselect feature in my Next.js project, utilizing states and setting them accordingly. However, I keep encountering this specific error: https://i.stack.imgur.com/m8zuP.png whenever I click on this: https://i.stack.imgur.c ...

Troubleshooting FabricJS: Object manipulation is disabled until a common selection is made

I am currently in the process of developing a product configurator with Vue and FabricJS. To set up my canvas, I used this.canvas = new fabric.Canvas("canvas"); <template> <div id="wrapper"> <div id="left"></div> &l ...

Leverage the data from a local JSON file within a web application built with Vue CLI 4.2.3

I need to use a JSON file to store some data and utilize them in the components. [ { "heroTitle": [ "Banner image", "assets/images/banner/sunset.jpg", "sunset.jpg" ], } ] The above JSON is an example, and below is my compone ...