What is the mechanism by which the outer array detects that the inner array has finished iterating?

How does the outer array in Javascript know when the inner array has completed its iteration? I am recursively iterating through the array below and would like to understand how the outer function or array can determine when the inner array has finished.

 {
  "rules": [
    {
      "id": 1,
      "value": "ABC"
    },
    {
      "id": 2,
      "value": "PQR"
    },
    {
      "id": 3,
      "value": "XYZ"
    },
    {
      "rules": [
        {
          "id": 10,
          "value": "ST"
        },
        {
          "id": 12,
          "value": "UI"
        }
      ]
    },
    {
      "id": 5,
      "value": "5XYZ"
    }
  ]
}

Using a recursive function to iterate through the array.

The desired output is: ABC, PQR, XYZ, 5XYZ Within Group: ST, UI


Edit1

var message = '';
var infoMessage = getMessageData(false);

function getMessageData(isGroup) {
  angular.forEach(rulesArray, function(v, k) {
      if (rulesArray.id === undefined) {
        message += getMessageData(true);
      } else {
        message += v.value;
        if (isGroup) {
          message += 'Within Group: ' + v.value;
        }
      }
    });
}

Answer №1

If my understanding is correct, a potential solution could be structured as follows:

Concept

  • Arrange the array based on objects with rules and reinsert them
  • Iterate over the array and perform checks
    • If an object has an id, append the value to the response
    • If an object has rules, employ recursion to retrieve the response and append it

var data = { "rules": [{ "id": 1, "value": "ABC" }, { "id": 2, "value": "PQR" }, { "id": 3, "value": "XYZ" }, { "rules": [{ "id": 10, "value": "ST" }, { "id": 12, "value": "UI" } ] }, { "id": 5,   "value": "5XYZ" } ] }

const key = 'rules';
data.rules.sort(function(a,b){
  return +(key in a) - +(key in b);
});

function getMessage(obj) {
  return obj.reduce(function (p, c, i, a){
    if('id' in c) {
      p += c.value + (i !== a.length -1 ? ', ': '');
    }
    
    if('rules' in c) {
      p += getMessage(c.rules);
    }
    return p;
  }, '')
}

console.log(getMessage(data.rules))

Answer №2

To organize the collection and processing of all items in the rules with a mechanism for adding the group phrase, you can create a queue.

function manageData(array) {
    var queue = array.slice(),
        group = array.length,
        temp,
        result = '';

    while (queue.length) {
        temp = queue.shift();
        if (temp.rules) {
            Array.prototype.push.apply(queue, temp.rules);
            continue;
        }
        if (--group) {
            result += (result && ', ') + temp.value;
            continue;
        }
        result += ' Within Group ' + temp.value;
    }
    return result;
}

var dataset = { rules: [{ id: 1, value: "ABC" }, { id: 2, value: "PQR" }, { id: 3, value: "XYZ" }, { rules: [{ id: 10, value: "ST" }, { id: 12, value: "UI" }] }, { id: 5, value: "5XYZ" }] };

console.log(manageData(dataset.rules));

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

What is the best way to find information in a multi-page table?

I've implemented a table with pagination and search functionality to look up data within the table. However, currently the search only works within the current page of the table rather than searching the entire dataset. Is there a way to modify the se ...

Switch from using Vue.js to Nuxt.js for improved functionalities and performance

I need to modify the following vue.js code snippet. Here is the original code: computed: { ...mapGetters('user/auth', ['Id']), }, async mounted() { await this.doFetchCustomer(this.Id) }, methods: { async doFetchCustomer(Id) { ...

Interactive YouTube Video Player that keeps video playing in original spot upon clicking the button

Currently, I'm working on a project that involves combining navigation and a video player within the same div container. Here is an image link And another image link The concept is that when you click on one of the four boxes, a new video will appe ...

Utilize a WebGLRenderTarget in a recursive manner with the power of threejs and GLSL programming

As a newcomer to both ThreeJS and GLSL, I am exploring ways to reuse the output of a fragment shader in another shader, while also utilizing that same output in the subsequent frame of the same shader. Essentially, the output of the shader is dependent on ...

The Vue.js edit component is first organized by lodash before being saved

In my Vue.js component, I have a feature that allows users to edit items inline. I'm using lodash to sort the items by name, but the issue is that every time a key is pressed, the array gets sorted immediately and causes a strange position change. The ...

Why is Visual Studio Code not highlighting my nested multi-line JavaScript comment as I anticipated?

/*/*! what is the reason */ for this annotation*/ Can someone explain why the annotation is not working as expected in this scenario? I've already verified it in VS code. ...

Modifying Three.js light intensity on the fly

Is there a method I haven't discovered yet to adjust the light intensity of directional lights dynamically? What about ambient light? ambientLight = new THREE.AmbientLight(0xffffff); scene.add(ambientLight); directionalLightL = new THREE ...

Using an array as an argument for a Perl subroutine

I am working on a subroutine in Perl that takes an array as input, converts it into a CSV format, and then POSTs it to a URL. Here's what I have attempted so far: Here is an example array: [ 2823383062, 1411691539, 1411691541, 'outgo ...

Definition of union types in JavaScript using Typescript

Looking for assistance in creating a d.ts file for the union-type library found at https://github.com/paldepind/union-type Consider the following union type: let Maybe = Type({ Nothing: [] , Just: [Number] }) I am interested in setting up compi ...

Sort the list alphabetically in Vue.js by clicking a button

I've been experimenting with Vue.js and having some trouble figuring out how to dynamically sort a list when clicking a button. Although I managed to successfully sort the list using the orderedBeers method, I can only see the changes in the inspecto ...

The functionality of the `download` attribute within the `a` tag seems to be

I tried implementing the download attribute in my code using jQuery, but it doesn't seem to be functioning properly. data = /images/myw3schoolsimage.jpg a = $('<a>').attr('href', data).attr('download', 'image. ...

Angular reactive form encountered an issue with an incorrect date being passed

Currently, I am utilizing the PrimeNg calendar module to select a date. Here is the code snippet: <p-calendar formControlName="valid_till" [dateFormat]="'mm/dd/yy'"></p-calendar> Upon selecting a date like 31st J ...

Encountered an issue in Laravel 5.7 JSONResource toArray method: Declaration must be compatible

I'm encountering an issue while trying to use the JSON Resource to Array converter in Laravel. Here is a snippet of my code: DataResource.php <?php namespace App\Http\Resources; use Illuminate\Http\Request; use Illuminate&bso ...

Developing the slicing functionality using the GetSlice method in F# interface

In F#, there is support for "slice expressions", which enable operations on arrays like myArray.[3 .. 5]. This feature, as defined in the F# 4.0 language specification (section 6.4.7), involves calling a GetSlice method after parameter conversion for one-d ...

How can you integrate Dygraph into your React project alongside redux?

Lately, I've been facing some challenges while trying to integrate Dygraph into React (utilizing Redux). The Dygraph wrapper packages available on NPM don't seem to cooperate. Furthermore, the conventional method of using: <div id="graph"> ...

Is there a way to share the Username and Password without the need to manually input it?

My goal is to develop a C++ application for my classmates at school. Currently, they are required to visit our school's website and navigate to the login page. Once there, they enter their username and password, log in, and proceed to find their spec ...

Utilizing Checkbox to Filter Data in Javascript

Looking for guidance on Javascript as a beginner. I'm attempting to filter and update data based on checkbox selections. The issue lies with Dataset3, where I aim to update the dataset dynamically once checkboxes are selected or deselected. I am stru ...

Creative Wrapping with EaselJS

Most canvas frameworks have a built-in feature for controlling word wrapping using maxWidth and maxHeight parameters. While setting the maxWidth in EaselJS is straightforward, is it possible to efficiently set a maxHeight for text as well? ...

Understanding the reason why "undefined" is occurring in Javascript

Can anyone help me understand why the alert at the start is showing "undefined"? The alerts are displayed in this order: "success!" "Data" (the correct value) "undefined" I have gone through several threads and found that the issue usually arises du ...

What am I doing wrong that causes me to repeatedly run into errors when trying to build my react app?

While attempting to set up a react.js web application in VScode using "npm," I encountered the following errors: npm ERR! code ERR_SOCKET_TIMEOUT npm ERR! errno ERR_SOCKET_TIMEOUT npm ERR! network Invalid response body while trying to fetch https://registr ...