UnionGhost
UnionGhost

Reputation: 3

How to count elements inside all nested arrays


I recently started learning JavaScript and ran into a problem.
I wrote a little code that counts elements inside a nested array, but the code breaks when adding an element to the first nested array. I don't understand what the problem is.

var clothes = [
    ['cap', 'scarf'],                 //-- When adding a new element, the counter breaks
    ['T-shirt', 'shirt', 'trousers'], //-- When adding a new item, the counter works fine
    ['boots', 'sneakers']             //-- When adding a new item, the counter works fine
];

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 help and explain why the error occurs only when adding to the first nested array?

Upvotes: 0

Views: 2237

Answers (3)

dale landry
dale landry

Reputation: 8600

You could use an iterator that will add 1 (iterator++) each time the function finds a new value within the nested arrays. I use a forEach nested within another forEach loop in the example below.

var clothes = [
  ['cap', 'scarf', 'hat'], //-- Added a new element no breaky
  ['T-shirt', 'shirt', 'trousers'], //-- When adding a new item, the counter works fine
  ['boots', 'sneakers'] //-- When adding a new item, the counter works fine
];

var totalItems = function() {
  let total = 0 //<-- iterator
  clothes.forEach(items => {
    items.forEach((item) => {
      total++ // iterate by one each time around
    })
  })  
  return total
}

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

Upvotes: 0

Mordred
Mordred

Reputation: 3941

You have a couple issues. Your for loops need to check for < clothes.length because <= will check an extra value that is not in your array (array's are 0-based, array.length is 1-based). You also are reassigning the total each time through the for-loop, and you are returning from the for loop after going through the loop. Your inner loop also keeps increasing the value of total every time creating numbers that will grow drastically.

This modification will fix all those problems in a much more concise manner.

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

ES6 way:

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

Upvotes: 1

Deniz Firat
Deniz Firat

Reputation: 159

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
    }
};

just edit your code like that.Seems like your second for condition looks for not existed index.

Upvotes: 0

Related Questions