5

I have an example of nested array:

var testArray = [1,2,[3,4,[5,6],7],8,9,[10,11],12];

Here is my function for getting nested array length:

Array.prototype.getLength = function() {
  var sum = 0;
  function getMultiLength(array) {
    for (count = 0; count < array.length; count ++) {
      sum ++;
      if (!array[count].length) {
        getMultiLength(array[count]);
      }
    }
  }
  getMultiLength(this.valueOf());
  return sum;
};

My expectation for result would be 12, but instead what I got is infinite loop:

testArray.getLength(); //infinite loop

Anyone know why and how to get nested array length?

Trung0246
  • 689
  • 1
  • 10
  • 21

9 Answers9

10

Problem with your code

Your existing code fails because the check for recursing is backward. You want to recurse if the length is non-zero. So it should be

  if (array[count].length) getMultiLength(array[count]);
  else sum++;

As your code stands, getMultiLength will be called even if array[count] is not an array (because if array[count] is not an array, length will be undefined). So it will keep recursing forever. This would be pretty easy to figure out by just stepping through your code in the debugger.

By the way, you don't need this.valueOf(). That is the same as this in this case.

Tweaking your code

But actually, you could streamline your code by eliminating the unnecessary inner function, and using the return value of the recursive calls:

Array.prototype.getLength = function() {
  let sum = 0;
  for (let count = 0; count < this.length; count ++) {
    sum += this[count].length ? this[count].getLength() : 1;
  }
  return sum;
};

Some people might prefer to write this using reduce:

Array.prototype.getLength = function() {
  return this.reduce((sum, elt) => 
    sum + (elt.length ? elt.getLength() : 1), 0);
};

Another solution using flattening

An alternative solution is to flatten the array, then find the length of the flattened array. Here we use a generator to create a flattener which is real easy to read and understand (ES6 feature):

function *flatten(array) {
  for (elt of array) 
    if (Array.isArray(elt)) yield *flatten(elt);
    else yield elt;
}

var testArray = [1,2,[3,4,[5,6],7],8,9,[10,11],12];

console.log(Array.from(flatten(testArray)).length);

Alternative implementation of flatten

Or, use your own favorite implementation of flatten, such as this recursive version:

function flatten(value) {
  return Array.isArray(value) ? [].concat(...value.map(flatten)) ? value;
}

or in ES5

function flatten(value) {
  return Object.prototype.toString.call(value) === '[object Array]' ?
    [].concat.apply([], value.map(flatten)) :
    value;
}

Putting it on the Array prototype

If you insist on putting this on the prototype, then

Object.defineProperty(Array.prototype, 'getLength', {
  value() { return flatten(this).length; }
});

Use defineProperty to make this property non-enumerable, non-configurable etc.

Trung0246
  • 689
  • 1
  • 10
  • 21
2

All the answers above are helpful, just adding another simple answer. Hope it's useful to someone in the future.

const getLength = arr => arr.flat(Infinity).length;

var testArray = [1,2,[3,4,[5,6],7],8,9,[10,11],12];
console.log(getLength(testArray));

We are using the flat() method here to flatten the array into a single array and then calculate the length of it. Note that we have passed the depth as Infinity because we want to go all the way deep and count the entire length.

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. In our case we will define the depth as Infinity

Read more on flat()

Kiran Dash
  • 4,816
  • 12
  • 53
  • 84
0

Try this :

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
var testArray = [1,2,[3,4,[5,6],7],8,9,[10,11],12];
var s = 1;
$.each(testArray, function(index, value){
    s = s + $(this).length; 
});
console.log(s);
Lakhan
  • 12,328
  • 3
  • 19
  • 28
  • 2
    An answer should not rely on a library that isn't tagged in the question or indicated in the code. At the very least it should explain the library that it requires. – RobG Oct 06 '16 at 04:40
  • No reason to drag in jQuery just for `each` -- use an ES6 method and point to a pollyfill – Jeremy J Starcher Oct 06 '16 at 04:50
  • @JeremyJStarcher I agree, but which ES6 method are you referring to? –  Oct 06 '16 at 05:10
  • @torazaburo - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach – Jeremy J Starcher Oct 06 '16 at 12:03
0

I used recursive call to find nested array length

var testArray = [1,2,[3,4,[5,6],7],8,9,[10,11],12];

var totalLen=0;
function length(arr){

   for(var ele in arr){
     if(Array.isArray(arr[ele])){
       length(arr[ele])
     }else{
         totalLen++;
     }
   }

}

length(testArray);
console.log(totalLen); //o/p 12

Improvised not using global variable here

var testArray = [1,2,[3,4,[5,6],7],8,9,[10,11],12];


var ArrayUtils=function(){

      var totalLength=0;

      function getNestedArrayLength(arr){

         for(var ele in arr){

             if(Array.isArray(arr[ele])){
               getNestedArrayLength(arr[ele])
             }else{
                 totalLength++;
             }
           }
      }

      function getLength(arr){

            getNestedArrayLength(arr);
            return totalLength;

      }

      return {
          getLength:getLength
      }
}

var aU=new ArrayUtils();
var length=aU.getLength(testArray);

console.log(length); //Op 12
Saravana
  • 1
  • 3
  • Can you try writing this in a way which does not use a global variable, and which returns the length as the function's value? –  Oct 06 '16 at 06:07
  • @torazaburo, can you check? above code i tried with out global variable – Saravana Oct 06 '16 at 06:30
0

There is a recursion call for nested arrays to count their non-array items:

var testArray = [1, 2, [3, 4, [5, 6], 7], 8, 9, [10, 11], 12];

Array.prototype.getLength = function () {
    function getMultiLength(array) {
        var sum = 0;
        for (var count = 0; count < array.length; count++) {
            if (Array.isArray(array[count])) {
                sum += getMultiLength(array[count]);
            } else {
                sum++;
            }
        }
        return sum;
    }

    return getMultiLength(this.valueOf());
};

alert(testArray.getLength());
Max Zuber
  • 1,217
  • 10
  • 16
0

Two methods that i would like to contribute with;

Recursive:

var testArray = [1,2,[3,4,[5,6],7],8,9,[10,11],12];
         flat = a => a.reduce((p,c) => p.concat(Array.isArray(c) ? flat(c) : c),[]);
       result = flat(testArray).length;
console.log(result);

Guerilla:

var testArray = [1,2,[3,4,[5,6],7],8,9,[10,11],12];
       result = JSON.stringify(testArray).match(/,/g).length+1;
console.log(result);
Redu
  • 25,060
  • 6
  • 56
  • 76
0
[].concat.apply([[]], testArray).length

for info on apply see:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply

rearThing
  • 632
  • 3
  • 9
  • 26
0

Hello here is the answer using Array.isArray to indentify if it is array or not, then recalling the function to do that one more time and so so on.

let test = [1, [2, [3, [4, [5, 6],7,[8,9,10,[11,12]]]]]];
let length = 0;
function len(array){
   for(let i in array){
      if(Array.isArray(array[i])){
          len(array[i])
       }else{
          length++
       }
    }
    return length;
};

len(test)
console.log(length)
-1

Try this:

Array.prototype.getLength = function() {
  var sum = 0;
  function getMultiLength(array) {
    for (var count = 0; count < array.length; count ++) {
      sum ++;
      if (array[count].length) {
        getMultiLength(array[count]);
      }
    }
  }
  getMultiLength(this.valueOf());
  return sum;
};

var testArray = [1,2,[3,4,[5,6],7],8,9,[10,11],12];

testArray.getLength()
  1. Do not use GLOBAL variable count.
  2. Why do you want to count array if it is empty?
Drag13
  • 5,859
  • 1
  • 18
  • 42
  • Answers should explain the OPs issue and how to fix it. Code–only answers are not particularly helpful. Have you tried this with an array whose elements are strings? – RobG Oct 06 '16 at 04:38
  • Do not give a fish, yeah? Please, look at the points mentioned below the answer. – Drag13 Oct 06 '16 at 04:53