Sorting arrays of objects in JavaScript using Lodash

I need help sorting an array of objects received from the server in ascending order based on the uid key, while keeping the original array intact. The array I'm working with has 2 elements in the data array. I want to analyze the uid values in each element and arrange them accordingly within the data array.

Although I attempted to use lodash for this task, it doesn't seem to be functioning correctly. I believe I am close to the solution and would appreciate some guidance:

// sort by:
console.log(res.results[0].data[0].row[1].uid)

_.forEach(res.results, function(obj) {
  _.forEach(data, function(anotherObj) {
    _.forEach(row, function(row) {
      data.row = _.sortBy(data.row, function(row) {
      return row[1].uid;
      });
    });
  });
});

Here is the array of objects retrieved from the server:

var res = {
  results: [{
    columns: ['large', 'medium', 'small'],
    data: [{
      row: [{
        sid: 13,
        tid: 427
      },
        {
          uid: 69,
          vid: 450,
          wid: 65
        },
        null],
      multirow: {
        nodule: [{
          xid: '427',
          properties: {
            yid: 13,
            zid: 427
          }
        },
          {
            aid: '450',
            properties: {
              uid: 69,
              bid: 450,
              cid: 65
            }
          }]
      }
    },
      {
        row: [{
          sid: 13,
          tid: 427
        },
          {
            vid: 432,
            uid: 65,
            wid: 61
          },
          null],
        multirow: {
          nodule: [{
            xid: '427',
            properties: {
              yid: 13,
              zid: 427
            }
          },
            {
              aid: '432',
              properties: {
                bid: 432,
                uid: 65,
                cid: 61
              }
            }]
        }
      }]
  }],
  errors: []
};

Answer №1

Using fewer loops is more efficient:

When looping through the results, you can directly sort the data array within each result as follows:
_.forEach(res.results, function(result) {
  result.data = _.sortBy(result.data, function(datum) {
    return datum.row[1].uid;
  });
});

By iterating over the results and sorting their data arrays in one loop, you eliminate unnecessary iterations. The callback used with sortBy specifies how to compare values within each data array.

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

Gather information from a JSON response using Volley library in Android

My goal is to retrieve data from the JSON response generated by PHP in Kotlin. Here is a snippet of the response: Log.d(TAG, "Login Response: $response") Login Response: {"data":{"name":"david","surname":nu ...

I possess a certain input and am seeking a new and distinct output

I am looking to insert a word into an <input> and see an altered output. For example, Input = Michael Output = From Michael Jordan function modifyOutput() { var inputWord = document.getElementById("inputField").value; var outputText = "print ...

Utilize the jQuery live() function on a single element

Looking for a solution to an issue with my Facebook-Like Chat on . Currently, the chat opens multiple bars when clicked, but only closes all at once. How can I make it so that each chat bar opens and closes individually when clicked? Any help would be ap ...

jQuery is experiencing compatibility issues with node-webkit

Currently, I am experimenting with node-webkit as a beginner in nodejs. The main content of my webpage consists of a simple html page which includes a script called main.js. To install jquery, I used the command npm install jquery index.html <!-- i ...

Encountered an error while trying to initiate MongoDB using dpd-d

Trying to kick off a Deployd application, I encountered some hurdles. Upon entering dpd-d in the terminal, an error message popped up: deployd v0.6.11 startup failed... Failed to initiate MongoDB Seeking to debug the issue by typing 'DEBUG=* dpd&apo ...

Having difficulty implementing a personalized color scheme for the mui component

Attempting to set the background color as midnightBlue but encountering an error: Error: Cannot read properties of undefined (reading '100') Upon reviewing the syntax, no errors were found. Perhaps this issue stems from a dependency problem? ...

Discover the Secret to Automatically Choosing Values in Select2 Multi-Select Dropdowns

I have a multiple select that looks like this: <select multiple="multiple" class="myList"> <option value="1" selected="selected">Apple</option> <option value="2" selected="selected">Mango</option> < ...

What is the rationale behind Numpy using a dimension of (n,) rather than (n,1)?

For quite some time, I have pondered over this issue. It doesn't bother me much when things go smoothly, but the inconsistency surfaces when attention to detail is lacking. Hence, I've decided to share my thoughts here. Let's consider the fo ...

Using JSON strings in an HTML data attribute isn't functioning as expected

I am working with checkboxes that have a data attribute called data-route. However, when hovering over them and trying to alert the values, I only get one letter or symbol. Here is my code snippet: foreach ($this->coords as $index=>$val ...

Effortlessly glide to the top of the webpage

After dedicating numerous hours to this task and being a newcomer to JavaScript/JQuery, I am still unsure of how to achieve the following: I have implemented a "back to top" anchor link in the footer of my pages that directs users back to the header. I am ...

Can you explain the significance of this code snippet 'true <=> false'?

Today I came across this piece of code: true <=> false. I'm a bit confused by it and don't really understand how it works. If anyone could shed some light on this expression for me, I would greatly appreciate it. For reference, this code ...

Tips for streamlining the marshaling process of complex, nested JSON structures

I am working with a JSON file that contains both static and dynamic data. Below is an example of the JSON structure: { "request": { "data": { "object": { "user": { "userid": "andmmdn", "ipaddr": "1.1.1.1", ...

Execute script when the awaited promise is fulfilled

I am looking to retrieve the URL of a cat image using the Pexels API through a script, and then set that image link as the source of an actual image element. I attempted to include some loading text to keep things interesting while waiting for the image l ...

Displaying JSON data offline with core data is a useful technique for creating efficient and user

I have successfully created a table view displaying labelName and labelUsername. I have also downloaded JSON data and stored it in a Core Data entity named Details with attributes name and username. The table view is currently showing data online, but I ne ...

Is it possible for me to use ts files just like I use js files in the same manner?

So I recently stumbled upon TypeScript and found it intriguing, especially since I enjoy adding annotations in my code. The only downside is that I would have to change all my .js files to .ts files in order to fully utilize TypeScript's capabilities. ...

Is it better to convert Mbox data to JSON or CSV format?

After utilizing the new download feature from Google, I now have a large .mbox file containing all of my Gmail data. Can someone provide me with a simple shell script to begin extracting and handling individual emails from this file? ...

Guide on adjusting the placement of mat-select-panel in Angular Material

In my current project, I am utilizing Angular Material Components and have been working on customizing mat-select. My goal is to make the select input appear like a dropdown similar to the native HTML select. I have managed to achieve a good effect using o ...

Segmentation fault occurs when modifying the value of an array in C

Help needed! I'm encountering a segfault when trying to change dna[i] to U. I've tried debugging the code, but I'm still unable to figure out the root cause of the issue. Furthermore, I initially used strcmp to compare the value at a positi ...

Use angular, javascript, or FormIo to set the cookie value to a dropdown list within a form as it loads

Currently, I am utilizing the Formio form within my Angular application. The registration form in my app consists of various fields, including State and city dropdowns that load values from State and city Formio resources. Whenever a user clicks on the Reg ...

Having trouble establishing a connection to the PostgreSQL database using Node JS/Express. Not receiving any response when making the request in Postman

Previously, the port was operational and running, but there was no response in Postman. Now, even though Express is included, it fails to be recognized. Can someone please assist me? I've been grappling with this issue for days now... I attempted to ...