Seeking assistance with creating a custom function to organize arrays within an object

I'm currently attempting to organize an Object that contains only properties which are arrays. My goal is to sort these arrays based on their length in order to ensure that when using Object.keys(), the resulting list will display all names in the correct order. Below is the code I've come up with so far (though I acknowledge that it may not be entirely accurate at the moment due to mental exhaustion):

function sortSetsByAmount(SETS, callback) {
    let sortedObject = {};
    
    for (let i = Object.keys(SETS).length - 1; i >= 0; i--) {
        let biggestSet = [];
        
        for (let j = Object.keys(SETS).length; j >= 0; j--) {
            if (SETS[Object.keys(SETS)[i]].length > biggestSet.length) {
                biggestSet = SETS[Object.keys(SETS)[i]];
            }
            
            if (j === 0) {
                sortedObject[Object.keys(SETS)[i]] = biggestSet;
            }
        }
    }
    
    callback(sortedObject);
}

}

Answer №1

To put it simply, you have the option to create a shallow copy of the original object with organized keys:

Object.keys(GROUPS)                                                  // array of keys from the original object
      .sort((key1, key2) => GROUPS[key1].length - GROUPS[key2].length)  // keys sorted by length of values in GROUPS
      .reduce((newObj, currentKey) => ({...newObj, currentKey: GROUPS[currentKey]}), {}) // shallow copy to new object

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

Ideas for utilizing jQuery to extract data from CSS files

Hey there, I'm facing an issue on my HTML page where I have jQuery included. In my CSS file, I have quite a lot of lines and I'm trying to figure out how to read all styles for a specific element from the external CSS file rather than the inline ...

The onsubmit function encounters an issue with invocation when implemented with Node.js

When I submit the form, I want to perform some validations. However, it seems like the validation function is not working as expected. The alert part does not appear when triggered. Here is the code snippet: function validation(){ alert("somethi ...

Utilize the power of Await Async while iterating through a massive JSON dataset

The data in the JSON file is quite extensive, weighing around 20MB. My goal is to ensure that the age returned is accurate, whether by waiting for the result or looping through the entire file. Currently, the output is always 0 even when the actual age is ...

What is the best way to target the nth-child() of a slotted element within a web component that utilizes multiple uniquely named slots?

I am struggling to select the second slotted item in a specific slot using slot[name=foo]::slotted(:nth-child(2)){, but it's not behaving as I anticipated. Even though the first foo slot is styled with green, the second one doesn't follow suit. ...

One method successfully updates the array within the data function, while a separate method continues to find the array empty

I am facing an issue in my app where I need to update an array. The process involves fetching data from the database and adding it to the array, which works fine. However, when I try to use this updated array in another method, it seems that the array is n ...

Extracting input value using HTML and JavaScript

Is there a way to utilize the content of a form field within a confirmation dialog box that pops up upon submission, as illustrated below? <form action='removefinish.php' method='post' accept-charset='UTF-8'> Role: < ...

Organizing content into individual Div containers with the help of AngularJS

As someone who is new to the world of AngularJS, I am currently in the process of learning the basics. My goal is to organize a JSON file into 4 or 5 separate parent divs based on a value within the JSON data, and then populate these divs with the correspo ...

Is there a way to generate a color image (RGB) by converting it into a three-dimensional array consisting of individual pixels?

One issue I'm facing involves manipulating the RGB values of a sample image to alter its appearance. I first extract the pixel data, store it in a 3-dimensional array, and then attempt to convert it back into an image, but encounter an error. I under ...

Creating a precise search query to locate specific IDs within an array

After reviewing this document: { "_id" : ObjectId("xxx"), "users" : [ { "_id" : ObjectId("xxx") }, { "_id" : ObjectId("yyy") ...

Tips on choosing just the selected checkbox values

In my CodeIgniter view, I am utilizing AJAX to post data to my controller. <script type="text/javascript"> $(document).ready(function(){ // find the input fields and apply the time select to them. $('#sample1 inp ...

What is the proper method for utilizing the .done or .complete functions in conjunction with .toggle in jQuery?

I am struggling to understand the proper usage of .complete or .done after .toggle in jQuery. My goal is to have the button's text change after the toggle animation finishes, but I'm not sure if I'm chaining them correctly. The jQuery docume ...

Efficient method for initializing integer arrays

Is there a more concise method to initialize an array ranging from 1 to a specified number using a variable? int nums=5; int[] array= Enumerable.Range(1,nums).ToArray(); Perhaps utilizing LINQ or some array function? ...

Determining when all $http requests have completed in AngularJS

After running multiple $http calls, I need to trigger an event only when all of them have been processed. Additionally, I must be informed if any call has failed along the way. Despite attempting solutions found on stackoverflow, such as using an intercept ...

Parsing JSON data in JavaScript with multiple objects

I just received a JSON Object from an HTTP request [ { "location": { "name": "Seattle, WA", "lat": "47.604", "long": "-122.329", "timezone": "-7", "alert": "", "degreetype": "F", "imagerelativeurl": "http:&b ...

An error of undefined Angular Service/Factory has occurred

I created a factory service called siteCollection: spApp.factory('siteCollection', function(){ return { usersObject : [], getUsers : function (){ $().SPServices({ operation: "GetUserCollectionFromSite", completef ...

Should classes/interfaces/functions be consistently prefixed with the App acronym as a best practice?

As I delve into my Angular project, I find myself contemplating the idea of using the App acronym as a prefix for all Classes, Interfaces, and Functions. This practice is commonly seen in tag components, where adding the App acronym helps avoid conflicts i ...

What is the best way to refresh the innerHTML of a div using the values from a JavaScript array when new elements are added to it?

I currently have an array with three items, along with four buttons - each designed to add a new item to the array. Although the process of adding items into the array using the buttons is successful, I am facing an issue with the display within the div e ...

What is the best way to connect a text box to a nested object in the state of a React component?

Solving a React Debugging Dilemma In my current project, I'm developing an office add-in using a React-based starter kit and TypeScript. Unfortunately, debugging has been a challenge as I am unable to access detailed error messages from React in my s ...

How can I retrieve the rating value in AngularJS Bootstrap after submitting a form?

I successfully incorporated the bootstrap star rating feature in an angularjs project. Although everything is functioning properly, I am encountering an issue with retrieving the final rating value after submitting the form. Below is the code snippet: // ...

Arranging elements based on specific coordinates

const renderTimeSlots = () => { const timeSlots = []; for (let i = parseInt(workStartsAt); i <= parseInt(workEndsAt); i++) { if (i !== 0) { timeSlots.push( <div className="flex flex-row cursor-pointer"> ...