Storing the array with the highest length in a temporary array using Javascript

I am currently working with two arrays that can be of equal length or one may be longer than the other.

My goal is to determine the longest array if they are not equal in length, and then use this length to control a loop.

$.ajax({

    url: "/static/Data/q_learning.json",
    dataType: "json",
    cache: false,
    async: true,
    success: function (data) {

        var data2 = data;
     
        $.ajax({

            url: "/static/Data/sarsa.json",
            dataType: "json",
            cache: false,
            async: true,
            success: function (data1) {
                var data1 = data1;
                var json_data = data2;
                var json_data1 = data1;

                json_data = json_data[Object.keys(data2)[0]];
                json_data1 = json_data1[Object.keys(data1)[0]];
                var result = [];
                var biggest = [];

                switch (json_data) {
                    case json_data.length > json_data1.length:
                        biggest = json_data;
                        break;
                    case json_data.length < json_data1.length:
                        biggest = json_data1;
                        break;
                    case json_data1.length > json_data.length:
                        biggest = json_data1;
                        break;
                    case json_data1.length < json_data.length:
                        biggest = json_data;
                        break;
                    default:
                        biggest = json_data1;
                }

                console.log(biggest);
                for (var i in biggest)
                    result.push([i, json_data[i], json_data1[i]]);

                console.log(result);

To determine the longest array, I compare their lengths and assign the larger one to a temporary array called "biggest."

If the arrays are of equal length, it doesn't matter which one is assigned as they both have the same length.

While this logic works sometimes, I am facing an issue where the longest array is not always correctly being assigned to the "biggest" temporary array. https://i.sstatic.net/mOrD1.png

The graph above illustrates the two sets of data on the same timeline, with one set being longer than the other.

When I adjust one variable higher than the other, the graph changes to reflect this difference. However, setting the other variable higher results in them being equal, as shown in the image below. https://i.sstatic.net/GwrNM.png I feel like the solution is right in front of me, but I can't seem to figure it out.

I would greatly appreciate any assistance or suggestions. Thank you!

Answer №1

After some investigation, I finally cracked the problem. The issue lied in obtaining the size of an array within a JSON object.

With the following code snippet, the puzzle was successfully solved.

json_data = json_data[Object.keys(data1)[0]];
json_data1 = json_data1[Object.keys(data2)[0]];
var json_data_size = Object.keys(json_data).length;
var json_data1_size = Object.keys(json_data1).length;
var result = [];
var biggest = [];

if(json_data_size > json_data1_size){
    biggest = json_data;
}else if(json_data_size < json_data1_size){
    biggest = json_data1;
}else if(json_data_size == json_data1_size){
    biggest = json_data1;
}

console.log(biggest);
for (var i in biggest)
    result.push([i, json_data[i], json_data1[i]]);

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

Continuously transmitting PNG files to a server. I intend to instruct the receiving browser to automatically refresh at set intervals

I have a continuous task where my code is uploading a png to an http server every few seconds. I am looking for a way to implement some kind of marker that will trigger the browser to automatically refresh every 500ms, either through browser-side javascrip ...

Exploring the Realm of Javacript Template Literal Capabilities

Is it possible to define a variable inside a template literal and then utilize it within the same template? If this isn't feasible, it appears to be a significant feature that is lacking. const sample = tag` some random words, ${let myvar = 55} addit ...

Is there a method similar to insertBefore that works with arrays and/or HTMLCollections?

Is there a vanilla JavaScript or jQuery function that works like Node.insertBefore(), but for arrays and/or HTMLCollections? An example of what I'm looking for: var list = document.getElementsByClassName("stuff"); var nodeToMove = list[0]; var other ...

unexpected alteration of text sizing in mathjax within reveal.js presentations

Something strange is happening with the font size in my slides. The code for each slide is the same, but there is an unexpected change between the 3rd and 4th slide. I cannot figure out what is causing this discrepancy. Oddly enough, when I remove the tit ...

Incorporating the Revolution Slider jQuery plugin within a Vue.js environment

Currently, my goal is to transform an html project into a vue application. The initial project utilizes a jquery plugin for Revolution slider by including them through script tags in the body of the html file and then initializing them: <script type= ...

Updating the chosen option using jQuery

Is there a way to change the currently selected option using jQuery? <select name="nameSelect" id="idSelect"> <option value="0">Text0</option> <option value="1">Text1</option> <option value="2" selected>Text ...

Unknown custom element error in Laravel and Vuetify

I encountered errors in my Laravel project, specifically with custom elements like this. [Vue warn]: Unknown custom element: <v-app> - did you register the component correctly? For recursive components, make sure to provide the "name" option. found ...

clearing all input fields upon submission in React Native

I need help resolving an error that occurs when I try to clear text input fields on a button press. Instead of clearing the fields, it throws an undefined error because I am trying to set the value as {this.state.inputTextValue} and then clear it using set ...

Retrieving HTML using jQuery Ajax POST

While attempting to utilize a jQuery Ajax POST request to fetch an HTML select menu from a PHP script, I encountered a perplexing issue. $.ajax({ type: "POST", url: "books/editions", data: dataString, cache: false, success: function(me ...

The issue of Next.JS fetch not caching data within the same request

I am faced with a straightforward setup where a Next.JS server-side component is responsible for fetching and displaying a post. The challenge lies in setting the page title to reflect the title of the post, requiring me to call my posts API endpoint twice ...

What is the best way to verify the [routerLink] values displayed from an Angular component string array?

I want to display the [routerLink] values coming from a string array in my Angular component. This is the TypeScript code: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-header', templateUrl: & ...

jQuery allows us to set two separate conditions for two distinct variables

I've written this function: settings_rc_left.on('click', function(){ var settings_list_last_element_id_one = settings_menu_element.attr('id') == 'r_02', settings_list_last_element_id_two = settings_menu_eleme ...

Make sure that a specific script is loaded prior to another script

I'm struggling to understand how scripts are loaded on a page. I have jQuery plugins that rely on other scripts. Specifically, I am using the timeago jQuery plugin. I have loaded these scripts in the head in the following order: <script src="< ...

Implementing a Singleton Pattern in ReactJS using Context API for Asynchronous Operations

My current implementation involves using a hook: function useFollowUser() { const isFollowing = useRef(false); return (userId) => { if(isFollowing.current) return; // mutual exclusion isFollowing.current = true; ... updat ...

Error encountered while trying to access `cookies.js` file in the `axios` module located at `../node_modules/axios/lib/helpers/`. The specific

Every time I attempt to retrieve data using axios.get(url), an error is thrown. Despite trying numerous solutions, nothing seems to work and this issue has persisted for quite some time. Any assistance that can be provided would be greatly appreciated. Er ...

Using only if-else statements and else-if conditions in JavaScript, arrange four numbers in order

How can I arrange 4 numbers in ascending order using only if-else and else-if statements in JavaScript without utilizing the sort function? ...

Looking to arrange an object by the value of a nested object in Typescript/Angular?

I'm currently developing an Angular 9 application focused on covid-19 cases, and I need to arrange my objects by the value of nested objects. Here is the dataset that I want to organize alphabetically based on the 'state' field values: stat ...

Error encountered while compiling NextJS: Unexpected use of single quotation mark in jsx-quotes

I can't seem to compile my NextJs 13 app without encountering errors. Take a look at my shortened eslintrc.js file below: module.exports = { env: { browser: true, es2021: true, }, extends: [ 'plugin:react/recommended', ...

Selenium unable to interact with Javascript pop-up box

I am currently working on automating a feature for our web application, specifically a form of @mentioning similar to Facebook. On the front end, when a user types @ into a text input, the API is called to retrieve the list of users and display them in a b ...

Querying a Mongoose nested schema

I've created the following schema: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const ProjectSchema = require('./project.js') const ClientManagerSchema = new Schema({ name : { type : String, required ...