What is the method for combining sub-subarrays and calculating their total length based on their sub-array index?

I am dealing with an array that contains sub-arrays, each of which may have different lengths. For example:

let arrayA = [
              [['a']            , ['b','c','d']],  //lengths  1  and  3 
              [['e','f','g','z'], ['h','i','j']],  //lengths  4  and  3
              [['k','l']        , ['m','n']]       //lengths  2  and  2 
                                                   //sums     7  and  8
             ]

The goal is to calculate the sum of the lengths of each sub-subarray based on the index of the sub-array it belongs to:

let arrayB = [[7],[8]] 

What would be the most effective approach to accomplish this task?

Answer №1

To easily summarize the array, you can utilize the reduce function. For iterating through the inner array, you can use forEach.

let arrayWithNestedArrays = [[["a"],["b","c","d"]],[["e","f","g","z"],["h","i","j"]],[["k","l"],["m","n"]]];

let finalResult = arrayWithNestedArrays.reduce((accumulator, currentValue) => {
  currentValue.forEach((object, index) => {
    accumulator[index] = accumulator[index] || [0];
    accumulator[index][0] += object.length;
  })
  return accumulator;
}, []);

console.log(finalResult);

Answer №2

To make the array smaller, you can use the `length` property to calculate the sum when mapping through it. After that, encapsulate the results in a new array.

var array = [[['a'], ['b', 'c', 'd']], [['e', 'f', 'g', 'z'], ['h', 'i', 'j',]], [['k', 'l'], ['m', 'n']]],
    result = array
        .reduce((r, a) => a.map(({ length }, i) => (r[i] || 0) + length), [])
        .map(a => [a]);

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

Answer №3

Start by creating a new array containing the length of only the first sub-array from the original array. Next, use the slice method to create another array consisting of elements from index 1 up to its length from the original array.

Then iterate over the arrays using the forEach method and access the index within the loop.

let arrayA = [
  [
    ['a'],
    ['b', 'c', 'd']
  ],
  [
    ['e', 'f', 'g', 'z'],
    ['h', 'i', 'j', ]
  ],
  [
    ['k', 'l'],
    ['m', 'n']
  ]
]

let initialElem = arrayA[0].map((item) => {
  return [item.length]
})
let secElem = arrayA.slice(1, arrayA.length).forEach(function(item, index) {
  if (Array.isArray(item)) {
    item.forEach(function(elem, index2) {
      initialElem[index2][0] = initialElem[index2][0] + elem.length
    })
  }

})
console.log(initialElem)

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

The hardware acceleration feature is not functioning correctly

When I set android:hardwareAccelerated="false, the video ends up running in the background instead of the foreground. However, if I change it to android:hardwareAccelerated="true, the marquee text and other static images start flickering. ...

There was a mistake: _v.context.$implicit.toggle cannot be used as a function

Exploring a basic recursive Treeview feature in angular4 with the code provided below. However, encountering an error when trying to expand the child view using toggle(). Encountering this exception error: ERROR TypeError: _v.context.$implicit.toggle i ...

Creating a Form with Dynamic HTML when Button is Clicked

I have been working on enhancing the functionality of my website app located at , but unfortunately, I have not been successful so far. My goal is to introduce a vendor information form with just one click of a button and then enable users to add products ...

How can I transform my jQuery code into a React Component?

When it comes to updating the CSS of an element in React, I initially turned to jQuery but later discovered that is not recommended. So now I am seeking guidance on how to achieve this task properly without using jQuery. If necessary, I can provide additi ...

Component updates are not working in VueJS

My Vue 1 component requires an object as a prop that needs to be filled by the user. This object has a specific structure with properties and nested inputs. The component is essentially a modal with a table containing necessary inputs. I want to perform v ...

Creating a custom calculator using Javascript

As a beginner in Javascript, I am seeking assistance in creating a simple calculator that can add numbers as buttons are clicked and display the running total. For example: If I click the button "20," it should display the number 20. Then, if I click the ...

Executing a JQuery function from varying environments

While this question may seem basic, I am having trouble understanding the behavior described. I have written some JavaScript code and I am puzzled why the second call to foo does not work. You can find the code in this JSFiddle link. $.fn.foo = function( ...

Error: The function setDarkTheme is not defined

Every time I click on the Dark button to apply dark theme on my page, I encounter an error. It seems like the error lies in the onClick function of the button and I can't seem to figure it out. Error message App.js import { useState } from 'rea ...

Show the entire image at its original size within an HTML5 Canvas of specific dimensions by utilizing JavaScript and potentially CSS styling

Is there a way to display an image within an HTML5 Canvas of a specific height and width while maintaining the image's aspect ratio? I need the image to appear at 100% size within a scrollable container. The image I want to use is of a tree: '&a ...

Storing images in MongoDB using React.js

I'm currently facing an issue with uploading an image file from the client side to MongoDB. To achieve this, I am utilizing an Express server along with 'multer' and 'sharp' for image uploading. On the client side, I have a CRA a ...

Having trouble with [Object Object] errors in your hybrid app using Javascript?

I'm currently developing a hybrid app using Nuxt JS, Cordova, and Cordova Native Storage (essentially localstorage). During the process of saving an object to native storage and retrieving it on page load within the mounted() method, I keep encounter ...

How come it's not possible to modify the text of this button right when the function kicks off?

When I click a button, it triggers a JavaScript function. The first line of code within the function uses jQuery to change the HTML of the button. However, the button's text does not update in the browser until after the entire function has completed, ...

Combining arrays of objects while maintaining data integrity in PHP

I am dealing with two arrays of objects: Array One: $array1 Array ( [0] => stdClass Object ( [id] => 100 [name] => John Doe ) [1] => stdClass Object ( [id] => 101 ...

The comparison between exposing and creating objects in a Nodejs router file

Recently, I began using expressjs 4.0.0 and was impressed by the express.Router() object. However, a dilemma arose when I moved all my routes to another file - how do I expose an object to the routes file? In my server.js file: ... var passport = ...

Loop through each item in the collection with attributes that contain the character '@'

Below is a data dump of $v containing an object: object(SimpleXMLElement)[69] public '@attributes' => array 'identifier' => string 'FC7C5117-8FF9-4FF4-86D2-F139EDE6EA74-19726-00011178F6D7A5AC' (length=59) ...

Manage multiple requests with Express JS and send back responses to the originating browser

Recently, I built a custom Express JS API that deals with user data, specifically an application with various form fields. The main purpose of my Express JS endpoint is to manage server requests and responses, providing feedback to the user's browser ...

Developing a structure array from a file in the C programming language

My goal is to create an array of structures in C. Despite my efforts, I am encountering warning messages related to reading in a two-character (number/colour) and the program only seems to read zero for every value from the file. #include<stdio.h> ...

Encountering the error "Attempting to pass properties to a second screen in react-native results in 'Undefined is not an object (evaluating 'this.route')'"

Currently, I am facing an issue while attempting to transfer properties from one screen to another in react-native using expo. The error message "Error 'Undefined is not an object (evaluating 'this.route')'" keeps appearing every time. ...

Angular can be used to compare two arrays and display the matching values in a table

Having two arrays of objects, I attempted to compare them and display the matching values in a table. While looping through both arrays and comparing them by Id, I was able to find three matches. However, when trying to display these values in a table, onl ...

Is it possible in core Node/Express to utilize a JSON file as a RESTful resource?

I have a JSON file with an array of 100 objects, each representing a person. I want to be able to retrieve ten person objects at a time from this JSON resource. Is there a way to implement a request in Node/Express where I can get back ten objects based on ...