简体   繁体   中英

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. ?

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

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

我会那样做...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM