Anuja vinod
Anuja vinod

Reputation: 109

How to count array elements inside an array in javascript?

I have an array as follows in nodejs

 var dataary=[];
    dataary=[ [ 'reg_no', 'slno', 'name', 'email', 'rollno' ],
    [ 'int', 'int', 'varchar', 'varchar', 'int' ],
    [ '100', '11', '255', '255', '100' ] ]

I need the count of array elements.As i do dataary.length it will return 3. But i need the count as 5 (count of elements inside array).How can i get the count of elements. ?

Upvotes: 2

Views: 9837

Answers (3)

oae
oae

Reputation: 1652

I would do it that way...

dataary.reduce((count, innerArray) => count + innerArray.length, 0);

Upvotes: 0

Manikant Gautam
Manikant Gautam

Reputation: 3591

Iterate through loop and get length of each individual array .The forEach() method executes a provided function once for each array element.

var dataary=[];
    dataary=[ [ 'reg_no', 'slno', 'name', 'email', 'rollno' ],
    [ 'int', 'int', 'varchar', 'varchar', 'int' ],
    [ '100', '11', '255', '255', '100' ] ,
    [ '1', '2', '3' ]]
    dataary.forEach(function(element) {
    console.log(element.length);
    });

Upvotes: 0

David Vicente
David Vicente

Reputation: 3111

With map you can get all lengths in one array and then you can sum them or do whatever you want to do.

var allLengths = dataary.map(element => {
   return element.length;
});

Upvotes: 3

Related Questions