Matthew Sirkin
Matthew Sirkin

Reputation: 93

How can I check the size of an array containing sub arrays?

I want something along the lines of array1.length from the below array:

var array1 = {
 sub1: [1,2,3],
 sub2: ["K","J","H"],
 sub3: ["Mango","Armada","Leffen","Mew2king"],
 sub4: ['1/8"', '3/16"', '1/4"'],
};

Right now I'm getting the following outputs:

console.log(array1) //Object {sub1: Array[3], sub2: Array[3]...}
console.log(array1.length) //undefined
console.log(array1[1]) //undefined
console.log(array1[1].length //Cannot read property 'length' of undefined

Where am I going wrong?

Upvotes: 1

Views: 214

Answers (6)

Aks
Aks

Reputation: 395

See Converting JSON Object into Javascript array

var array1 = {
 sub1: [1,2,3],
 sub2: ["K","J","H"],
 sub3: ["Mango","Armada","Leffen","Mew2king"],
 sub4: ['1/8"', '3/16"', '1/4"'],
};
alert("Size : "+Object.keys(array1).map(function(k) { return array1[k] }).length);

OUTPUT

Size : 4

HOW IT WORKS

Converting the keys to an array and then mapping back the values with Array.map Then, can get the length of this array. Gg wp.

NB : You can also create a var at the beginning and then use it to all your process.

Upvotes: 0

Coss
Coss

Reputation: 453

You could always do something like this:

var array1 = [[1,2,3],["K","J","H"],["Mango","Armada","Leffen","Mew2king"],
 ['1/8"', '3/16"', '1/4"']];
var flatArray = [].concat.apply([],array1)

This will flatten the array so you can use length etc.

Upvotes: 0

Jimmy Adaro
Jimmy Adaro

Reputation: 1405

array1 is a JSON object. So

array1.subArray.length

should work

Upvotes: -1

Sankar
Sankar

Reputation: 7107

Try this...

var array1 = {
  sub1: [1, 2, 3],
  sub2: ["K", "J", "H"],
  sub3: ["Mango", "Armada", "Leffen", "Mew2king"],
  sub4: ['1/8"', '3/16"', '1/4"'],
};

console.log(array1.sub1.length,array1.sub2.length,array1.sub3.length,array1.sub4.length);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386654

You have an Object, not an Array.

You could iterate over the keys and get the length of the arrays inside of the object.

var object = { sub1: [1, 2, 3], sub2: ["K", "J", "H"], sub3: ["Mango", "Armada", "Leffen", "Mew2king"], sub4: ['1/8"', '3/16"', '1/4"'] };
Object.keys(object).forEach(function (key) {
    console.log(object[key].length);
});

Upvotes: 1

BrTkCa
BrTkCa

Reputation: 4783

array1 not is a array, is a object. sub1 and so on are arrays, then you can:

array1.sub1.length; // returns 3

Upvotes: 1

Related Questions