Streamlining a collection of nested arrays

Can someone help me understand how to calculate the total number of elements in nested arrays like [[1,2,3],[1,2],[]]? I'm looking for a way to find the sum of all the entries in the arrays. For this specific example, the answer would be 5. The content within the arrays is not important to me, just their lengths.

Thank you for your assistance!

Answer №1

If you're looking for a solution, one approach is to utilize the reduce method.

let collection = [[1,2,3],[1,2],[]];

const total = collection.reduce((accumulator, array) => accumulator += array.length ,0);

console.log('Total items: ' , total);

Answer №2

Tareq's solution works well for the given scenario.

However, if you encounter an array with deeper nesting or potentially empty subarrays, the following code snippet can be more helpful:

var a=[[],[1,2,3],[1,2],[],[[4,[5,,,6]]],[]];
console.log(a.toString().replace(/^,|,+(?=,|$)/g,'').split(',').length);

This might seem a bit excessive, but now the code will handle any empty elements within the array and remove them accordingly. The regular expression specifically targets single commas at the start, multiple commas in between, and single commas at the end of the string.

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

Despite successful installation, node remains elusive on Ubuntu VPS

After installing node using NVM with version 0.25.0, I specifically installed node version 0.10.32. However, upon running node -v, the following error is displayed: -bash: /root/.nvm/v0.10.32/bin/node: No such file or directory Similarly, when executing ...

Using parameters in a nested function in Javascript

I need help passing an argument to a function nested within another function; function add() { let x = arguments[0]; function s(num) { return num + x; } } add(2)(3) //trying to pass the second argument to 'function s'. I want the re ...

Having trouble deciphering the logic behind my bug detection process in the Three.js Verlet Cloth Simulation on GPU

I'm facing difficulty grasping the logic I am working on with Three.js and the GPUComputationRenderer developed by yomboprime. (https://github.com/yomboprime/GPGPU-threejs-demos/blob/gh-pages/js/GPUComputationRenderer.js) My goal is to create a simp ...

The JSON file now contains the name of the variable rather than its value

When receiving a json from an API I created, it contains various values and one of them needs to be appended to another json object. Here is the original json where the data should be added: originalOrder = { "name": 1, "su ...

Error Alert: Unable to access property 'top' of undefined object

After tackling a series of bugs in the short script below, I've finally smoothed out the kinks. To witness a functional demonstration, click on this link: http://jsfiddle.net/XG24G/2/ I apologize for providing an extensive context, but when I insert ...

Exploring the traversal of nested objects in handlebars

After retrieving the data from the backend and successfully displaying it in the console, I am facing a challenge in rendering it out in handlebars. Here is my object: Any suggestions on how to effectively render this data in handlebars? ...

Encountered an issue while trying to register a service worker: "[ERROR] Cannot import statement outside

With the utilization of register-service-worker, the boilerplate for registerServiceWorker remained untouched. /* eslint-disable no-console */ import { register } from 'register-service-worker'; if (process.env.NODE_ENV === 'production&ap ...

Automatically collapse the Bootstrap4 Dropdown Menu upon clicking the select element

After tackling my previous issue on Stack Overflow, I stumbled upon a new question that has been bothering me. The problem arises when users click on the arrow to reveal advanced search options, as the form drops down as expected. However, when a user cli ...

What is the best way to send two arguments to model.fetch() in backbone.js?

Currently, I am in the process of creating a simple user authentication system. My goal is to send both the username and password as parameters to the Node.js server on the back-end. These parameters will be used in a database query to retrieve user detail ...

ReactJS Form: Updates in Parent Component State Result in Child Field Being Cleared and Props Remaining Unchanged

I have devised a ReactJS code for an interactive form that allows the collection of student details. The beauty of this form is that it can accommodate any number of students with ease. In this setup, the parent component is known as App and the child comp ...

Building a React component to display JSON data in a tabular format

I am trying to create something similar to the layout in the following link: Table example Imagine I have two arrays: names: ["Prisma 2 Case", "PP-Bizon", ...] imgs: ["img1.png", "img2.png", ...] One array contain ...

Ways to deactivate just the Clicked button in a mapped over component

Utilizing the request variable, I am displaying an array of objects on the page. Each object in the array contains properties such as question, correct_answer, and incorrect_answer. Moreover, I have implemented a state called disable which toggles between ...

Ways to access PromiseValue in XMLHttpRequest with JSON

Is there a way to access an array that is within the PromiseValue instead of receiving Promise {<pending>} When I use .then(data => console.log(data)), I can see the array in the console log. However, my requirement is to display this array on an ...

Whenever I navigate to a new page in my NEXTJS project, it loads an excessive number of modules

I am currently working on a small Next.js project and facing an issue where the initial load time is excessively long. Whenever I click on a link to navigate to a page like home/product/[slug], it takes around 12 seconds to load due to compiling over 2000 ...

Modifying the delimiters of underscore templates with Gruntjs

I'm currently working on creating a JSP page and I've noticed that the template delimiters used by JSP's are also used by underscore. After looking through the documentation at this link: https://github.com/gruntjs/grunt/wiki/grunt.template ...

Issue with character encoding in jQuery-ui tabs

Special characters in Swedish are replaced when configuring the tabTemplate option. For instance, using "ö" in the href attribute: var $tabs = $("#tabs").tabs('option', 'tabTemplate', '<li><a href="#ö">#{label}</ ...

Top tips for utilizing numerous XMLHttpRequests efficiently

I am attempting to retrieve 8 JSON objects from 8 different URLs. I have stored the query string that needs to be modified in an Array, and I am looping through it using a for loop. Below is my code: var index = ["ESL_SC2", "OgamingSC2", "cretetion", "fre ...

What could be causing my function to not register with my EventListener?

I'm attempting to perform an action when I click on an element. I have added an eventListener to change the value of a variable upon clicking on that element. However, the eventListener is not working as expected. When I debug the code, it seems like ...

Unable to place within div

Utilizing HTML5 to implement the "DnD" function. There is a button that adds divs. I want to be able to drag items into these newly added divs. Currently, I can only drag into existing divs and not the ones added later. How can I resolve this issue ...

When you click the button, it will change colors. But when you click it again, it won't return to its original color

I am trying to implement a feature where clicking on the correct answer will change its color to green, while clicking on the wrong answer will change it to red. I also want to add an additional functionality: if the right-answer button is clicked twice, i ...