Skip to content Skip to sidebar Skip to footer

Count Elements In A Multidimensional Array

Ive got this code: loadData : function(jsonArray) { var id = $(this).attr('id'); for(var i in jsonArray) { $('#'+id+' tbody').append('Copy

Now, you can call countInObject(jsonArray[i]).

Solution 2:

Like this:

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

// Get the size of an objectvar size = Object.size(myArray);

Length of a JavaScript object

Solution 3:

Have a look to that fiddle : http://jsfiddle.net/Christophe/QFHC8/

key is

for (var j in jsonArray[i]) {

instead of

while (col <= jsonArray[i].length) {

Solution 4:

jsonArray[i].length will not work because jsonArray[i] is a dictionary not an array. You should try something like:

for(var key in jsonArray[i]) {
     jsonArray[i][key]
}

Solution 5:

I've been facing the same issue and I scripted a function that gets all the scalar values in a multidimensional Array/Object combined. If the object or array are empty, then I assume that it's not a value so I don't sum them.

functioncountElements(obj) {
  functionsumSubelements(subObj, counter = 0) {
    if (typeof subObj !== 'object') return1; // in case we just sent a valueconst ernation = Object.values(subObj);
    for (const ipated of ernation) {
      if (typeof ipated !== 'object') {
        counter++;
        continue;
      }
      counter += sumSubelements(ipated);
    }
    return counter;
  }
  returnsumSubelements(obj);
}

let meBe = { a: [1, 2, 3, [[[{}]]]], b: [4, 5, { c: 6, d: 7, e: [8, 9] }, 10, 11], f: [12, 13], g: [] };
const itution = countElements(meBe);
console.log(itution); // 13let tuce = [1,2];
console.log(countElements(tuce)); // 2console.log(countElements(42)); // 1

Or if you want to use this in production, you could even think about adding it to the Object prototype, like this:

Object.defineProperty(Object.prototype, 'countElements', {
  value: function () {
    functionsumSubelements(subObj, counter = 0) {
      const subArray = Object.values(subObj);
      for (const val of subArray) {
        if (typeof val !== 'object') {
          counter++;
          continue;
        }
        counter += sumSubelements(val);
      }
      return counter;
    }
    returnsumSubelements(this);
  },
  writable: true,
});

console.log(meBe.countElements()); // 13console.log([meBe].countElements()); // 13; it also works with Arrays, as they are objects

Post a Comment for "Count Elements In A Multidimensional Array"