What is the best way to arrange numerous objects within an array?

Here is the code snippet I am working with:

const info = {
  detail : {
   id: "1",
   name: "aa", 
   category: [
    {
      id:"11",
      order:0,
    },
    {
      id:"33",
      order:5,
    },
    {
      id:"3",
      order:1,
    },    
   ] 
  },

  detail2 : {
   id: "2",
   name: "aaa", 
   category: [
    {
      id:"111",
      order:3,
    },
    {
      id:"33",
      order:1,
    },
    {
      id:"3",
      order:2,
    },    
   ] 
  }
}

I am trying to rearrange the category objects based on their order. I attempted to use the following piece of code:

info.category.sort((x, y) => {
  return x.order - y.order || x.order.localeCompare(y.order);
});

Unfortunately, this implementation ends up replacing the elements and only retaining the last one. There seems to be something missing for it to work as intended.

The desired output should look like this:

const finalInfo = {
  detail : {
    id: "1",
    name: "aa", 
    category: [
    {
      id:"11",
      order:0,
    },
    {
      id:"3",
      order:1,
    },
    {
      id:"33", 
      order:5, 
    },    
    ] 
  },

  detail2 : {
    id: "2",
    name: "aaa", 
    category: [
    {
      id:"33", 
      order:1, 
    },
    {
      id:"3", 
      order:2,
    },
    {
      id:"111", 
      order:3, 
    },    
    ] 
  }
}

How can I achieve that?

Answer №1

Here is a code snippet for you to try:

const information = {
  user : {
   id: "1",
   name: "Alice", 
   group: [
    {
      id:"11",
      order:0,
    },
    {
      id:"33",
      order:5,
    },
    {
      id:"3",
      order:1,
    },    
   ] 
  },

  user2 : {
   id: "2",
   name: "Bob", 
   group: [
    {
      id:"111",
      order:3,
    },
    {
      id:"33",
      order:1,
    },
    {
      id:"3",
      order:2,
    },    
   ] 
  }
}

Object.keys(information).forEach(key => {
  const item = information[key];
  item.group = item.group.sort((a, b) => {
    return a.order - b.order || a.order.localeCompare(b.order);
  });
  
  return item;
});

console.log(information);

Answer №2

Follow these instructions (CREDIT TO: flymaster)

Object.keys(inputData).forEach(item => {
const value = inputData[item];
value.category = value.category.sort((element1, element2) => {
return element1.rank - element2.rank || element1.name.localeCompare(element2.name);
});

return value;
});

console.log(result);

Answer №3

Try utilizing the Object.values method alongside a forEach loop and implement sorting.

Object.values(data).forEach(({ group }) =>
  group.sort((a, b) => {
    return a.order - b.order || a.order.localeCompare(b.order);
  })
);

const data = {
  item: {
    id: "1",
    name: "aa",
    group: [
      {
        id: "11",
        order: 0,
      },
      {
        id: "33",
        order: 5,
      },
      {
        id: "3",
        order: 1,
      },
    ],
  },

  item2: {
    id: "2",
    name: "aaa",
    group: [
      {
        id: "111",
        order: 3,
      },
      {
        id: "33",
        order: 1,
      },
      {
        id: "3",
        order: 2,
      },
    ],
  },
};

Object.values(data).forEach(({ group }) =>
  group.sort((a, b) => {
    return a.order - b.order || a.order.localeCompare(b.order);
  })
);

console.log(data);

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

Guide on how to prevent Paste (Ctrl+V) and Copy (Ctrl+C) functionalities in a TextField within MaterialUI

Is there a way to restrict the Paste (Ctrl+V) and Copy (Ctrl+C) functions in a specific TextField within MaterialUI? I am currently working with ReactJs ...

Transforming values from a multidimensional array into key-value pairs in a flat array and omitting a prefix from one of the values

Here is a structure of an array I am currently working with: Array ( [0] => Array ( [option_id] => 10820 [option_name] => PREFIX_FIRST_OPT_KEY [option_value] => FIRST_OPT_VALUE [autol ...

Retrieving data with JQuery when encountering an XHR error

When I send a jQuery AJAX request and receive a successful response, I am able to retrieve my JSON data. However, if the response code is anything other than 200, I am unable to access the data in the jQuery callback function. This data is crucial as it co ...

PHP is used in the while loop, but the output should be displayed using JavaScript

I need help with modifying my code to display individual MySQL results in message boxes using JavaScript. Currently, when I click on a message box, it only shows one result for every button. My goal is to have each button display its own unique message fr ...

Using webpack to load the css dependency of a requirejs module

Working with webpack and needing to incorporate libraries designed for requirejs has been smooth sailing so far. However, a bump in the road appeared when one of the libraries introduced a css dependency: define(["css!./stylesheet.css"], function(){ &bsol ...

"Transitioning seamlessly from one element to another in the script

How can I transition from one function to another function in a script element? How do I transfer the field validator value to the second function? <script> $('#card_number').validateCreditCard(function(result) { if ...

Learn how to default export React with withRouter, all while taking advantage of Material UI's makeStyles

I have been working on integrating Material UI makeStyles with class components, passing useStyles as props while default exporting it in an arrow function. export default () => { const classes = useStyles(); return ( <LoginClass classes={cl ...

Storing the current date and time in a MySQL database using NodeJs

I'm having an issue inserting a DATETIME field into my MySQL database. var dt = require('moment')().format('YYYY-MM-DD HH:mm:ss'); pool.query( `insert into login(id, id_utente, data_login) values(NULL,?,?)`, [result ...

Chrome Extension: Sending Data from Panel Window to Popup - A Step-by-Step Guide

I've been developing a Chrome extension that displays a window (popup.html) containing a button for playing videos when the extension icon is clicked. Upon clicking the play button, another window created using window.create of type panel opens up. Th ...

Show User-Specific Information Using DataTable

After conducting extensive research, I have been unable to find a suitable example to reference. My goal is to customize my DataTable so that it only displays data relevant to the currently logged-in user (admin accounts will have access to all data). I am ...

Expanding and collapsing all divs with a single click using Jquery

I've gone through numerous resources but I'm still struggling to understand this concept. I have implemented a simple accordion based on this tutorial and now I want to include an "expand/collapse all" link. While I was able to expand all the ite ...

The destruction of scope is not activated

Check out my issue in action with this plunkr demo. The problem I'm encountering is quite straightforward: manually calling $destroy or removing the element does not trigger the $destroy event. function link(scope, element, attrs) { // Manually ca ...

Unit testing an API built with Express and Mongoose using Jest

I have decided to implement a TDD approach for a user API that I am working on. Specifically, I am looking to add unit tests for two functions: userRegister and userLogin. Here is the code snippet from my app.js: 'use strict' const express = r ...

Creating interactive tabs within the HTML document with AngularJS

Trying to customize the tab layout on my HTML page and I have a code similar to this: <form name="requestForm"> <div class="form-group col-md-6 md-padding"> <div class="text-primary"> <h3>Create Request</h3> ...

Looking for a custom textured circle in three.js?

Is there a way to create a circle with a texture on one side in three.js without using sprites? I was considering using THREE.CylinderGeometry, but I'm unsure of where to add the "materials" in the new THREE.CylinderGeometry(...) section. Any suggest ...

wait until the CSS parser retrieves the CSS files

I am trying to ensure that the page is rendered only after the CSS has been loaded. The function css_parser.getCSSFiles() reads the file asynchronously and sends the CSS content to the variable css.cssFile. How can I make sure that res.render waits for t ...

HTML code featuring multiple dropdown menus, each equipped with its own toggleable textarea

I have multiple HTML drop downs, each triggering a textarea based on the selection. Currently, I'm using show and hide JavaScript functions for each question individually. Is there a way to streamline this so that I don't have to write separate c ...

Tips for making Slider display the next or previous slide when span is clicked

I have implemented a mix of bootstrap 3 and manual coding for my project. While the image thumbnails function correctly when clicked, the span arrows do not navigate to the next or previous images as intended. Below is the code snippet: var maximages ...

Performing multiple asynchronous tasks using RxJS by running Array.prototype.map in parallel batches or queues

Imagine having an array of variables, such as: [Sasha, Misha, Caitlyn, ...String] (string[]) with a sizable length of about 10k elements. If you want to run an asynchronous parallel task with these elements, but not all at once like Promise.all, rather in ...

Tips for transferring information from a promise into an array

I'm trying to populate an array (coursesArray) with data from a promise and then use these values elsewhere. I am using the node-fetch library to make API queries. The issue I'm facing is that when I log the array inside the promise, it contains ...