how can I organize an array of objects in JavaScript by the 'categoryname' property from my dataset in alphabetical order utilizing the mergesort algorithm

Here is the data list that needs to be sorted alphabetically based on the categoryName using merger sort


    const filteritem = [
      {
        "categoryName": "admission",
         /* rows details */
      },
      {
        "categoryName": "officialdocument",
         /* rows details */ 
      ],
      {
        "categoryName": "syallabus",
         /* rows details */
      },
      {
        "categoryName"":"Binodkhatricv",
         /* rows details */
      }
    ] 

I can implement different sorting algorithms like merge sort, bubble sort, depth search etc. But for now, I will use merge sort to achieve the desired outcome. The final result should resemble the structure mentioned above.


    filteritem=[
    {categoryName:"admission"...},
    {cateogryName:"Binodkhatricv"..},
    {categoryName:"officialdocument"...},
    {categoryName:"syallabus"...}
    ]

Answer №1

To experiment with organizing the data, you might want to consider using the sort function like this:

const filteritem = [
    {
      "categoryName": "admission",
      "rows": [
        {
          "uploaddate": "8/8/2022",
          "title": "binoddocs",
          "view": "https://firebasestorage.googleapis.com/v0/b/auth",
          "fullname": "bruno",
          "id": "B8QsXYVFH8fHt3PrBYUp"
        }
      ]
    },
    {
      "categoryName": "officialdocument",
      "rows":
        [{
          "file": null,
          "uploadedby": "bruno",
          "uploaddate": "6/27/2022",
          "title": "sudhikchaadmission",
          "view": "https://firebasestorage.googleapis.com/v0/b/auth",
          "id": "Z27GLizWnYTJvLQyYRQt"
        },
        {
          "view": "https://firebasestorage.googleapis.com/v0/b/auth",
          "uploadedby":"bruno",
          "uploaddate":"6/27/2022",
          "title":"ankitadmission",
          "file":null,
          "id":"rmcbUrg9TpFhQh5RLqva"
        }
      ]
    },
    {
      "categoryName":"syallabus",
      "rows": [
        {
          "fullname":"bruno",
          "view":"https://firebasestorage.googleapis.com/v0/b/auth",
          "title":"sudhir",
          "uploaddate":"8/15/2022",
          "id":"hi7QEOlBzzVLZ1QHYqlk"
        }
      ]
    },
    {
      "categoryName":"Binodkhatricv",
      "rows": [
        {
          "title":"binodtry",
          "fullname":"bruno",
          "uploaddate":"8/15/2022",
          "view":"https://firebasestorage.googleapis.com/v0/b/auth",
          "id":"o4EtP1xkbWMk1icp4uNH"
        }
      ]
    }];

    let sorted = filteritem.sort((a, b) => (a < b ? -1 : 1))
    console.log(sorted)

Answer №2

Utilize the localeCompare method to arrange the string, ensuring case sensitivity is disregarded by applying toLowerCase.

const filteritem = [
  {
    "categoryName": "admission",
    "rows": [
      {
        "uploaddate": "8/8/2022",
        "title": "binoddocs",
        "view": "https://firebasestorage.googleapis.com/v0/b/auth",
        "fullname": "bruno",
        "id": "B8QsXYVFH8fHt3PrBYUp"
      }
    ]
  },
  {
    "categoryName": "officialdocument",
    "rows": [
      {
        "file": null,
        "uploadedby": "bruno",
        "uploaddate": "6/27/2022",
        "title": "sudhikchaadmission",
        "view": "https://firebasestorage.googleapis.com/v0/b/auth",
        "id": "Z27GLizWnYTJvLQyYRQt"
        },
      {
        "view": "https://firebasestorage.googleapis.com/v0/b/auth",
        "uploadedby":"bruno",
        "uploaddate":"6/27/2022",
        "title":"ankitadmission",
        "file":null,
        "id":"rmcbUrg9TpFhQh5RLqva"
      }
    ]
  },
  {
    "categoryName":"syallabus",
    "rows": [
      {
        "fullname":"bruno",
        "view":"https://firebasestorage.googleapis.com/v0/b/auth",
        "title":"sudhir",
        "uploaddate":"8/15/2022",
        "id":"hi7QEOlBzzVLZ1QHYqlk"
      }
    ]
  },
  {
    "categoryName":"Binodkhatricv",
    "rows": [
      {
        "title":"binodtry",
        "fullname":"bruno",
        "uploaddate":"8/15/2022",
        "view":"https://firebasestorage.googleapis.com/v0/b/auth",
        "id":"o4EtP1xkbWMk1icp4uNH"
      }
    ]
  }
]

const result = filteritem.sort((a, b) => a.categoryName.toLowerCase().localeCompare(b.categoryName.toLowerCase()))

console.log(result)

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

The MUI Time picker fails to display the correct time value in the input field with proper formatting

My primary goal is to implement a MUI time picker with yup validation and react-hook-form. However, I am encountering an issue where the selected time from the time picker is not being updated in the text field as expected. https://i.sstatic.net/LVkgK.png ...

Error: The function `map` cannot be applied to `filteredProducts`

I encountered an issue stating that a function is not being recognized. Upon troubleshooting, I realized that the data retrieved using useState was not being saved in the products state. However, when using setProducts(res.data) console.log(res); t ...

Example of a line graph implementation using a d3 array as input

I am a d3 newbie and I am trying to learn by working with the d3.js line example. The code for this example is provided below. My goal is to adjust it to use model data that I already have in a json object format. However, I am struggling with translating ...

Struggling to retrieve the file parameter value with Angular.js and PHP?

I have encountered an issue while attempting to upload a file using Angular.js and PHP. Although I am able to successfully send the file parameter value, I am unable to retrieve it on the PHP side. Below is an explanation of my code. workspesh.html: & ...

Implementing TypeORM in an ExpressJS project (initialized using Express generator)

I am currently working on an ExpressJS project that was created using the Express generator. My goal is to integrate TypeORM into this project, but I am facing some challenges in achieving that. After attempting to modify the /bin/www file with the follow ...

JavaScript function that fetches data from local storage and displays it in an HTML table

I've been exploring how to incorporate a bootstrap datatable into my project. Rather than using pre-set data, I want to allow users to input their own data through a form and store it in localStorage. Understanding that I need to stringify and parse ...

Looking for assistance with overriding kendo UI validation requirements

I'm looking to customize the date validation in my code to validate the date as DD/MM/YYYY. Here's my current code snippet and I'm getting an error message that says: Unable to get property 'methods' of undefined or null referen ...

Using trigonometry, create random orbits in multiple directions around a central point in THREE.js

I'm attempting to create a swirling motion of multiple objects around a single Vector3 point, each moving in different directions to give the effect of swarming around the center. Instead of simply wrapping each object in a Container and applying ran ...

Ways to identify when an HTMLElement's size changes due to a percentage-based width setting

Currently, I am in the process of developing an Angular Component and have implemented the following CSS code: :host { display: block; width: 100%; } The main objective here is to ensure that the component remains as responsive as possible. However, ...

Mirror the image horizontally prior to saving

I'm working on a camera web app that has filters similar to Snapchat. I'm currently facing an issue where the image is mirrored because I'm using the front camera. Is there a way to flip the image before downloading it? Thank you for your re ...

Showing the elements of a python list in a dropdown menu on a webpage using AJAX

I'm currently utilizing Django and AJAX to create a chained dropdown feature. The user will initially choose a brand_name from a dropdown menu, and based on that selection, the names of all products made by that brand will be populated in a second dro ...

Converting a database query result into a JavaScript variable: A step-by-step guide

I've been struggling with this problem for a day now and I feel like giving up. My main goal is to export the query result as a string (specifically dataString) so that I can easily import it as a string in my external .js file. module.exports.getKl ...

The child's status is not displaying correctly

I am in the process of developing a blackjack app and facing an issue with re-rendering hands after the initial deal. I have tried updating the state in App.js and passing it to PlayerHand.js for rendering, but the child component does not refresh despite ...

Dynamic elements in ViewModel

Looking to parse the following JSON in .NET "currentData": { "Name": {"system": "wfdss", "canWrite": true }, "DiscoveryDateTime": { "system": "wfdss", "canWrite": true }, "Code": { "system": "code", "canWrite": false }, ... } Since these el ...

Using JQuery to emphasize selected radio button area

Can someone help me modify the code to highlight the checked radio button by adding or removing a class from the <span class " ui-message ui-state-highlight"> element? Below is the HTML and JS code: $(document).ready(function(){ $('# ...

Collaborate and reuse Typescript code across various Node projects

Imagine we have a project structured like this: webapps ProjectA SomeClass.ts Package.json ProjectB SomeClass.ts Package.json Common LoggingClass.ts Package.json The Common "LoggingClass" needs to import a module from NPM. Let's say that ...

Obtaining data from JSON arrays

My current challenge involves extracting data from the following link: and storing it in my database. However, I am encountering difficulties with manipulating the array in order to retrieve the last unix datetime. Despite multiple attempts to extract th ...

Issue with three.js hello world example: canvas fails to display

I am facing a challenge in getting this hello world example to work on my personal computer: http://jsfiddle.net/GKCx6/ You can access my current progress here: Although I have made several attempts, I am unable to render anything successfully. How shoul ...

Utilizing electron and Systemjs to import node modules

Is it feasible for systemjs to utilize require("remote").require("nodemodule") when the module cannot be located in its registry? A similar mechanism seems to be functioning when utilizing electron with typescript and commonjs modules... Has anyone succe ...

Creating a dynamic mouse trail effect using CSS and JavaScript without compromising element clickability

I'm looking to create a mouse trail that follows the cursor as it moves, made up of small icons or images that gradually fade out over time. I attempted to achieve this by overlaying a grid on top of all other elements on the page. The grid consists o ...