What is the best way to iterate through a collection of two or more arrays in order to determine the total length of all

https://i.stack.imgur.com/PpFlB.pngI currently have multiple Arrays containing various inputs

this.listNumber = [
  {
    "GenericQuestions": [
      {
          "input": "long",
      },
      {
          "input": "dog",
      },
      {
          "input": "",
      }
    ],
  },
  {
    "GenericQuestions": [
      {
          "input": "fred",
      },
      {
          "input": "barney",
      },
      {
          "input": "betty",
      }
    ]
  }
]

// There can be more Arrays

In the past, I used the getFilter Method to retrieve input results from a single Array

getFilter(index: string | number) {  // index being 0
    return this.listNumber[index].GenericQuestions.filter((c: { input: any }) => !!c.input).length;
} // returns 2

Now, I am trying to find a way to get the results of all filled out inputs from both Arrays.

I attempted

  const flatfile = this.listNumber.flat();
  console.log("flatfile", flatfile);

However, it seems to have failed because GenericQuestions are contained within separate objects.

Answer №1

Assuming you have an array called listNumbers structured like this:

this.listNumbers = [
    {
        "GenericQuestions": [
            {
                "input": "some text 1"
            },
            {
                "input": "some text 2"
            },  
            {
                "input": "some text 3"
            } 
        ]
    },
    {
        "GenericQuestions": [
            {
                "input": "some text 4"
            },
            {
                "input": "some text 5"
            },  
            {
                "input": "some text 6"
            }
        ]
    }
]

To extract the input fields from all arrays identified by "GenericQuestions", create a new array and populate it with the elements of every "GenericQuestions" array

const newArray = []

for (let object of this.listNumbers) {
    newArray.push(...object["GenericQuestions"])
}

This process will result in a single flat array that includes all input objects

newArray = [
    {
        "input": "some text 1"
    },
    {
        "input": "some text 2"
    },
    {
        "input": "some text 3"
    },
    {
        "input": "some text 4"
    },
    {
        "input": "some text 5"
    },
    {
        "input": "some text 6"
    }
]

Answer №2

Upon understanding your request correctly, the following code provides a solution:

let listItems = [{
    GenericItem: [{ value: "apple" }, { value: "banana"}, { value: ""}]
}, 
{
    GenericItem: [ {value: "orange"}, { value: "mango"}, { value: "kiwi" } ]
}];

let outputResult = listItems.map(item => item.GenericItem).flat().filter(entry=>!!entry.value);

console.log(outputResult);

Here is the expected output:

[
  { value: 'apple' },
  { value: 'banana' },
  { value: 'orange' },
  { value: 'mango' },
  { value: 'kiwi' }
]

Answer №3

Essentially, the task at hand involves adding up the number of non-empty input elements in your listNumber array. Sound familiar?

All you have to do is... well... sum things up like this:

let total_cnt = 0
for( let i = 0 ; i !== this.listNumber.length ; ++i ) total_cnt += this.getFilter(i)
console.log(total_cnt)

Alternatively, if you prefer a more functional approach:

const total_cnt = this.listNumber.reduce((total_cnt, _, i) => total_cnt + this.getFilter(i), 0)

No need to bother creating temporary arrays or rehashing existing getFilter code. Keep it DRY!

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

methods for transferring JSON data from JavaScript to PHP

I am trying to figure out how to parse JSON data from JavaScript to PHP. Here is my JavaScript code: var Dataconvert; var asetid = new Array(); $("#simpanmodifikasi").click(function(){ var table = $('#tableasal tbody' ...

Developing versatile form elements with Formik and the Yup library for React and Vite

I'm currently working on a React and Vite project where I'm trying to implement reusable form components using Formik and Yup, but I haven't been able to achieve it yet. I've created a component called <AppInputField/>, which is e ...

Tips for removing a row from a DataGrid column with the click of a button

I am facing a challenge with my data table that contains users. I am trying to implement a delete button for each row, but it seems like the traditional React approach may not work in this situation. Currently, I am utilizing the DataGrid component in the ...

Enhancing AngularJS: Revamping the isolated scope within a directive

I am seeking to develop a custom directive that can dynamically display changing data. To keep things simple, let's say I want it to show the current time and update every second. In the AngularJS documentation, there is an example similar to what I ...

CSS - Discovering the reason behind the movement of text post generation (animation)

I have a question regarding CSS animation, specifically the typewriting effect. I was able to successfully achieve the typewriting effect using animation. However, I noticed that even though I did not set any animation for transforming, once the text is g ...

What is a practice for utilizing navCtrl.push() with a variable storing a class name?

Currently, I am utilizing Visual Studio Code for Ionic 3 development with AngularJS/Typescript. In my code, I am using this.navCtrl.push() to navigate to different pages within the application. Specifically, I have two classes/pages named "level1" and "lev ...

Ways to address the issue of duplicated names in input fields

Currently, I am utilizing a React Hook Form hook known as useFieldsArray. This hook is responsible for rendering an array of fields, each containing an object with the data that will be transmitted via the input. One interesting feature is the ability to ...

How to handle redirection in React when encountering a 404 error with React

Hey there, I'm encountering an issue related to react router. Let's take a look at my App.js file where all the routes are defined: const App = () => ( <div className="App"> <MediaQuery minWidth={700}> {(matches ...

Is it possible to link the _id of a mongodb array to its corresponding clientId in another array?

I am facing a challenge with 2 arrays retrieved from my MongoDB database. The first array is called users and it contains user objects structured like this: [{ email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d1a1beb ...

Failure to display div upon onmouseover event

The div 'hidden-table' is causing issues as it does not display even though the style attribute 'display:none' has been removed. I have attempted to show the table separately outside of the echo statement, and it appears to work correct ...

Issues arise in Angular 4 when the "Subscribe" function is repeatedly invoked within a for/switch loop

My array of strings always changes, for example: ["consumables", "spells", "spells", "consumables", "spells", "consumables", "spells", "characters", "characters", "consumables"] I iterate through this array and based on the index, I execute different .su ...

The environmental variables stored in the .env file are showing up as undefined in Next.js 13

I am having trouble accessing the environment variables stored in my .env.local file within the utils folder located in the root directory. When I try to console log them, they show as undefined. console.log({ clientId: process.env.GOOGLE_ID, clien ...

Encountering a TypeScript error while trying to pass the myDecorator function as a decorate prop to React

Encountering a TS error that states: (property) decorate?: ((entry: NodeEntry<Node>) => BaseRange[]) | undefined Type '([node, path]: [node: any, path: any]) => { anchor: { path: any; offset: string | number; }; focus: { path: any; offset: ...

Calculating the volume of an STL file mesh using three.js

I'm currently trying to figure out how to determine the volume of an STL file. I've successfully managed to obtain the dimensions of the model using var box = new THREE.Box3().setFromObject( mesh ); var sizes = box.getSize(); However, when it c ...

My table elements are automatically being populated with <tr> elements thanks to Javascript

Upon viewing the screenshot: it is evident that each element is placed within its own tr. My preference is to have each element contained in a td and then wrap everything within a single tr. Here is the updated HTML structure: <div id='result&a ...

Create a dynamic form using JSON data and the Material UI library

Looking for assistance in creating a dynamic form on Next.js by parsing JSON files and generating the required components from the JSON data. Additionally, seeking guidance on utilizing the Material UI library for styling. Any examples or help would be g ...

What is the best way to retrieve the IDs of selected items in jQuery selectables?

I have a straightforward question that I've been struggling to find an answer to. When using jQuery selectables, I want to retrieve the ID of the selected list item when it's clicked. Here is an example of my list: <ol id="selectable"> ...

Having received a status code of 200 in Flask WebApp, I am still unable to access the page

Currently in the process of developing a webapp using Flask, I have created the homepage where users are required to input their phone number and password. Once entered, the system will send an OTP to the provided phone number. When clicking the signup bu ...

What are the connections between objects in ReactJS?

I have an array containing objects, and I want to extract a specific value from another array by using the key inside it as a search parameter. Specifically, I need to retrieve the name of an item based on its ID. The primary array: this.setState({ offer ...

Guide to encoding an array of objects into a URI-friendly query string using TypeScript

Just getting started with typescript and looking for some help. I have an input array structured like this: filter = [ { field : "eventId", value : "123" }, { field : "baseLocation", value : "singapore" } ] The desired format for ...