Ways to tally the number of elements within multiple layers of nested arrays


I just dove into learning JavaScript and encountered an issue.
I whipped up a simple code that tallies elements within a nested array, but for some reason, the code malfunctions when adding an element to the first nested array. The cause of this problem eludes me.

var clothes = [
    ['cap', 'scarf'],                 //-- Inserting a new element here causes the counter to malfunction
    ['T-shirt', 'shirt', 'trousers'], //-- Adding new items here works without any issues
    ['boots', 'sneakers']             //-- Adding new items here also doesn't pose any problems
];

var totalItems = function () {
    for (var i = 0; i < clothes.length; i++) {
        var total = 0;
        for (var k = 0; k <= clothes[i].length; k++) {
            total = total + clothes[k].length;
        }
        return total
    }
};

console.log('all clothes: ' + totalItems());

Error:

Uncaught TypeError: Cannot read property 'length' of undefined
at totalItems (test2.js:13)
at test2.js:31

Please provide assistance and elucidate why the error only occurs when modifying the first nested array.

Answer №1

You have a few issues to address. Make sure your for loops are checking for < clothes.length instead of using <=, as this will access an element that does not exist in your array (remember, arrays start at 0). Additionally, you are resetting the total value each time within the loop and prematurely returning from it. Furthermore, your inner loop is incrementing the total without any logic, causing it to increase exponentially.

To resolve all these issues efficiently, consider implementing the following revised code:

var calculateTotalItems = function () {
    var total = 0;
    for (var i = 0; i < clothes.length; i++) {
        total += clothes[i].length;
    }
    return total;
};

A more concise ES6 approach can be achieved with the code snippet below:

let calculateTotalItems = () => {
    let total = 0;
    clothes.forEach(entry => total += entry.length);
    return total;
}

Answer №2

const calculateTotalItems = function () {
    let totalCount = 0;
    for (let i = 0; i < clothes.length; i++) {
        for (let k = 0; k < clothes[i].length; k++) {
            totalCount += clothes[i][k].length;
        }
    }
    return totalCount;
};

Make sure to update your code according to the given instructions. It seems like the second loop condition may be incorrect.

Answer №3

You may utilize an iterator that increments by 1 (iterator++) each time the function discovers a new value within the nested arrays. In the example provided, I have used a forEach loop nested inside another forEach loop.

var clothingItems = [
  ['cap', 'scarf', 'hat'], //-- Added a new element without breaking
  ['T-shirt', 'shirt', 'trousers'], //-- The counter works correctly when adding a new item
  ['boots', 'sneakers'] //-- The counter works correctly when adding a new item
];

var totalItemsCount = function() {
  let total = 0 //<-- iterator
  clothingItems.forEach(items => {
    items.forEach((item) => {
      total++ // increment by one for each iteration
    })
  })  
  return total
}

console.log('Total number of clothing items: ' + totalItemsCount());

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

Challenges with Webpack sourcemaps

As I delve into learning nodejs and react, my current challenge lies in building bundle.js and debugging it within the browser. However, despite creating the bundle.map file, I am faced with errors as the webpack tab fails to appear in the browser. DevTool ...

Sorting techniques in c programming using bubble sort

As a novice c programmer, I set out to create a program that would determine the highest value in an array. My approach involved sorting the array using the Bubble sort method and then returning the first element as it should represent the highest value. H ...

Enable the feature for users to upload images to a specific folder within the Chrome extension without the need for

I need to implement a feature in my Chrome extension that allows users to upload images directly to a specific folder named "upload" without needing a submit button. <form action="/upload"> <input type="file" name="myimages" accept="image/*"> ...

Issue with Android Cordova: Unable to assign value to property 'text' because it is set to null

While attempting to run cordova prepare on my project, I encountered the following error : (node:11384) UnhandledPromiseRejectionWarning: TypeError: Cannot set property 'text' of null at updateProjectAccordingTo (C:\Users\Utilisateur&b ...

Increasing the variable by 1 in PHP will result in the variable value being incremented to 1

My issue involves incrementing a variable in my .php file code that changes the value in the database. After incrementing the acc_points variable by one, it updates the data in the MySQL database and then returns the data to the JavaScript, which alerts th ...

Tips on inserting table data into a textarea input using a button

Is there a way to display the text from the table in a textarea box when clicking the "add" button, without removing the data once it's added? I simply want the text "Add this text to textarea" to show up in the textarea box. https://jsfiddle.net/bj ...

Error in setting cookies using Javascript document.cookie on iOS with cordova-plugin-ionic-webview

Backend-sent cookies are successfully stored, but the app itself cannot set cookies. When running the code snippet below: document.cookie = "notified=1; path=/; expires=Tue, 19 Jan 2038 03:14:07 GMT"; console.log(document.cookie); An empty strin ...

How can we show pictures when a user clicks?

After creating a model for displaying images in a modal when clicked by the user, I encountered an issue. Whenever I try to access the images from the gallery within the modal content, it only displays a blank popup. I want the pictures from the image gall ...

Unable to retrieve jwt token from cookies

Currently, I am developing a website using the MERN stack and implementing JWT for authentication. My goal is to store JWT tokens in cookies. Despite invoking the res.cookie function with specified parameters (refer to the code below), I am facing difficul ...

What is the functionality of promisifyAll and what are the necessary conditions for it to operate effectively?

When it comes to promise libraries like bluebird, there is a function called promisifyAll that can convert async functions with callback patterns into promise-based functions using resolve(), reject(), or done(). But how exactly does this conversion proces ...

Troubleshooting problems with bot roles on Discord

After spending some time coding my bot, I encountered an issue when trying to add a role to a user who didn't already have it. Everything seemed to be functioning properly until I included the member.roles.add command. Despite having every possible p ...

JS glitch leading to oversized window dimensions - Issue with dropdown menu

I recently integrated a dropdown into my website using Foundation CSS. To see the dropdown in action, you can login with the credentials provided (username: stackoverflow password: testtest) on . However, I noticed that when logged in, the page on the rig ...

Tips for shutting down an HTML webpage with the help of JavaScript

Recently, I've been working on a project to implement a feature that automatically closes the website when an incorrect password is entered. However, I am fairly new to JavaScript and still in the early stages of learning. Below is the code snippet I ...

Filtering in AngularJS can be done by combining two fields at

I attempted to implement similar code for filtering my tasks, but it seems to be malfunctioning. When I use just one filter, everything works fine regardless of which one I choose. However, when I attempt to filter by the second input, it simply does not w ...

warning: issue detected with the password value in jquery

Why is the following script generating an incorrect JavaScript alert message? <script type="text/javascript> $('#cpassword').change(function() { var pass=$('#password').val(); alert(pass); var cpass=$(& ...

Problems Arising from the Content Menu and Tab Opening Features of a Chrome Extension

I am encountering an issue with the code below not displaying the context menu when text is selected on the webpage. Currently, when I select text, the context menu fails to appear. Code function getword(info,tab) { if (info.menuItemId == "google") ...

When deciding between utilizing a Javascript animation library and generating dynamically injected <style> tags in the header, consider the pros and cons of each

We are currently in the process of developing a sophisticated single-page application that allows users to create animations on various widgets. For example, a widget button can be animated from left to right with changes in opacity over a set duration. Ad ...

Passing parent HTML attributes to child components in Angular 2

Is there a way to pass HTML attributes directly from parent to child without creating variables in the parent's .ts class first? In the sample code below, I am trying to pass the "type=number" attribute from the parent to the app-field-label component ...

What could be causing the slow loading time of my Shopify App developed using Next.js (React)?

I recently followed a tutorial at However, I am facing severe performance issues with my app. It loads extremely slowly when changing tabs, whether it's running on ngrok, localhost, or deployed on app engine. I'm new to React, Next.js, and Shop ...

Designing an uncomplicated password authentication system without embedding the password itself [Using PHP, Javascript, and MySQL]

I'm in the process of setting up a basic login prompt for my local website. I initially experimented with Javascript, but I'm looking for a way to avoid hardcoding the password. Users receive their passwords via email, so there's no need for ...