How to locate the lengthiest array nested within an object (which is nested within another object) using JavaScript

I have a complex structure of objects containing arrays, nested within other objects. Here is an example of the structure:

My goal is to determine the longest array of objects within each parent object. Using the example below:

For ObjectOne - the longest array is B.

For ObjectTwo, the longest array is C.

mainobj = {
    ObjectOne: { 
        A: [ 
             { x: 'd', y: 'e'},
             { x: 'd', y: 2} 
           ],
        B: [ 
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'} 
           ],
        C: [ 
             { x: 'd', y: 'e'} 
           ]
    },
    ObjectTwo:{ 
        A: [
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'}
           ],
        B: [
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'}
           ],
        C: [
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'},
             { x: 'd', y: 'e'}
           ]
    }
}

To implement this logic:

var size = Object.values(mainobj).length

However, accessing nested arrays requires a different approach, like this:

var size = Object.values(mainobj)[0].length

If you're looking for help on a similar issue, check out this question. Thank you in advance for your assistance!

Answer №1

To retrieve the keys of the largest inner arrays, you can create an object for each outer key and then form an array containing those keys.

var obj = { objOne: { A: [{ x: 'd', y: 'e' }, { x: 'd', y: 2 }], B: [{ x: 'd', y: 'e' }, { x: 'd', y: 'e' }, { x: 'd', y: 'e' }, { x: 'd', y: 'e' }], C: [{ x: 'd', y: 'e' }] }, objTwo: { A: [{ x: 'd', y: 'e' }, { x: 'd', y: 'e' }, { x: 'd', y: 'e' }], B: [{ x: 'd', y: 'e' }, { x: 'd', y: 'e' }], C: [{ x: 'd', y: 'e' }, { x: 'd', y: 'e' }, { x: 'd', y: 'e' }, { x: 'd', y: 'e' }, { x: 'd', y: 'e' }] } },
    output = Object.keys(obj).map(function (k) {
        var o = obj[k];
        return {
            key: k,
            items: Object.keys(o).reduce(function (result, value, index) {
                if (!index || o[result[0]].length < o[value].length) {
                    return [value];
                }
                if (o[result[0]].length === o[value].length) {
                    result.push(value);
                }
                return result;
            }, [])
        };
    });

console.log(output);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To filter your object and keep only arrays with the maximum length:

var mainObj = {
    1: {
        A: [
            { x: 'd', y: 'e' },
            { x: 'd', y: 2 }
        ],
        B: [
            { x: 'd', y: 'e' },
            { x: 'd', y: 'e' },
            { x: 'd', y: 'e' },
            { x: 'd', y: 'e' }
        ],
        C: [
            { x: 'd', y: 'e' }
        ]
    },
    2: {
        A: [
            { x: 'd', y: 'e' },
            { x: 'd', y: 'e' },
            { x: 'd', y: 'e' }
        ],
        B: [
            { x: 'd', y: 'e' },
            { x: 'd', y: 'e' }
        ],
        C: [
            { x: 'd', y: 'e' },
            { x: 'd', y: 'e' },
            { x: 'd', y: 'e' },
            { x: 'd', y: 'e' },
            { x: 'd', y: 'e' }
        ]
    }
};

var res = {};

Object.keys(mainObj).forEach(key => {
    var maxLength = 0, maxLengthArrayName, maxLengthArray;
    Object.keys(mainObj[key]).forEach(arrayName => {
        if (mainObj[key][arrayName].length > maxLength) {
            maxLengthArrayName = arrayName;
            maxLengthArray = mainObj[key][arrayName];
            maxLength = mainObj[key][arrayName].length;
        }
    });
    res[key] = { [maxLengthArrayName]: maxLengthArray };
});

console.log('res: ', res);

// Accessing the max length array for each sub-object of mainobj:

var subObject = '1';
var maxLengthArrayName = Object.keys(res[subObject])[0];
var maxLengthArray = Object.values(res[subObject])[0];

console.log(`max length array name for sub-object ${subObject}: `, maxLengthArrayName);
console.log(`max length array for sub-object ${subObject}: `, maxLengthArray);

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

Repeated requests to http in Angular when using Subscribe

I'm relatively new to angular and experimenting with building a dashboard application. This dashboard is rather comprehensive, housing over 50 unique charts. In order to streamline the process, I opted to fetch all the necessary data for these charts ...

Enhance security in AngularJS by enabling data sharing between controllers and implementing callback functions for authentication

Currently, I am engaged in building an Angular front-end application, aiming to keep things simple without relying on tools like breeze or restangular while still maintaining code integrity. However, I have noticed that my code tends to become overly compl ...

Interactive Thumbnail Selection for HTML5 Video

Having trouble with creating thumbnails? I managed to solve the cross-domain issue using an html2canvas PHP proxy. No error messages in the Console, but the thumbnails are unfortunately not showing up - they appear transparent or white. Here is a snippet ...

`Misconceptions in understanding AngularJS directives`

I am currently working on a new app that includes both a header and main view, utilizing directives. At first, I had the directive in its own file but decided to relocate it into app.js in order to resolve an issue. Throughout this process, I have experim ...

Can you explain the concept of a "cURL" and guide me on how to use it effectively?

I'm currently working on setting up a Lyrebird application, but I only have a basic understanding of javascript and php. Despite my efforts to implement a cURL request from , I've encountered issues trying to get it to work in both javascript and ...

Is there a way to incorporate a custom method into a JQuery tab widget?

Need assistance with extending the functionality of the jQuery UI tabs widget by implementing a new method for all instances. Attempted using both $.extend() and jQuery.widget(), but encountered an issue where the newly added method remains undefined when ...

Unidentified properties in mongoose query

Currently, I am utilizing MongoDB and Mongoose along with TypeScript. I have encountered an issue with the following scenario: Here is the model definition I have created: export default conn.model<AdminInterface & Document>('Admin', a ...

JavaScript code that triggers a function when the mouse is moved over a description box on a

As a beginner in the field of Computer Science, I recently embarked on a project to create a website for sharing science articles with students. The goal is to spark curiosity and interest in science through this platform. One key feature I wanted to inclu ...

Deciphering the ins and outs of the jQuery each function - Surprising

I'm currently trying to understand how the each function works. In this specific scenario demonstrated in this fiddle here, my goal is to iterate through the selected elements of a list box individually. Initially, I anticipated an output like this: ...

Using AngularJS ng-src within an Iframe

I have been trying to dynamically set the source of an iframe using a scope variable, but it keeps appearing blank. Here is what I attempted: <div ng-repeat="url in urls"> <div ng-click="testAlert(url.domain)"> <iframe ng-src="{{ url ...

Retrieve a specific value from an array of objects by searching for a particular object's value

Here is an example of an array of objects I am working with: $scope.SACCodes = [ {'code':'023', 'description':'Spread FTGs', 'group':'footings'}, {'code':'024', ' ...

"Troubleshooting: Issue with ng-click in AngularJS not triggering ng-show

I can't figure out why my ng-click isn't showing the ng-show message. I've tried searching for a solution but no luck. Here is my controller function: $scope.showLogoutMessage = function() { $scope.logoutmsg = true; }; This is my Logi ...

Modifying two distinct charts according to the choices made in two independent dropdown menus

In my current project, I am facing a challenge with integrating two separate dropdowns containing UFC fighter names. The goal is to display a plot showing the KD (Knockdown) data for the selected fighters over time when their names are chosen from both dro ...

The JSON page does not display the image

I am facing an issue where the images are not displaying on both the JSON page and the HTML page, even though the image source name is being outputted. How can I ensure that the images show up on the HTML page? Thank you for taking the time to help. line ...

Calling a JavaScript function using string parameters

Lately, I've stumbled upon an issue when attempting to execute a function with multiple arguments. <button type = "button" id = "clickmepls" onclick = killButton("clickmepls", "grave1")> Click me please </button> The definition of the fu ...

Transforming a flat TypeScript array into a nested object structure

I'm working on implementing a user interface to offer a comprehensive overview of our LDAP branches. To achieve this, I plan to utilize Angular Materials Tree as it provides a smooth and intuitive browsing experience through all the branches (https:// ...

Tips for automatically refreshing the Parent page once the modal form is closed in ASP.NET Core

I am currently using asp.net core mvc 5 along with EF Core 5. On a specific page, there is a button that triggers a modal form to appear when clicked. This allows the user to create a new person. Upon submitting the modal form, a person is created and ass ...

Error: "$$" not defined in this context

I am currently working on generating a dynamic pie chart programmatically with the intention of transforming it into a reusable React Component. The main idea is to have an interactive pie chart where each slice expands into a full pie when clicked. I came ...

I can't find my unit test in the Test Explorer

I'm currently working on configuring a unit test in Typescript using tsUnit. To ensure that everything is set up correctly, I've created a simple test. However, whenever I try to run all tests in Test Explorer, no results are displayed! It appear ...

Retrieving JSON information stored in a JavaScript variable

I'm feeling a bit embarrassed to admit it, but I am still learning the ropes when it comes to Javascript development. I've hit a roadblock and could really use some help from the experts here. Thank you in advance for all the assistance this comm ...