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. ?
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. ?
Share Improve this question asked Dec 19, 2017 at 11:13 Anuja vinodAnuja vinod 1093 silver badges11 bronze badges 5- Wele to Stack Overflow! Please take the tour and read through the help center, in particular How do I ask a good question? Do your research, search for related topics on SO, and give it a go. If you get stuck and can't get unstuck after doing more research and searching, post a minimal reproducible example of your attempt and say specifically where you're stuck. People will be glad to help. Good luck! – T.J. Crowder Commented Dec 19, 2017 at 11:13
-
1
use
dataary[0].length
. – Vipin Kumar Commented Dec 19, 2017 at 11:14 -
1
Note: It just so happens that the length is 5 for all of the arrays in
dataary
, but it could just as easily be that they each had different lengths. – T.J. Crowder Commented Dec 19, 2017 at 11:14 -
But i need the count of elements inside each array
- loop through the main array and extract the length of each sub array? - stackoverflow./questions/12502843/… – Nope Commented Dec 19, 2017 at 11:17 -
1
But i need the count as 5
You need to get answer as 5 or 15? – Shalitha Suranga Commented Dec 19, 2017 at 11:17
3 Answers
Reset to default 3With 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);
});
I would do it that way...
dataary.reduce((count, innerArray) => count + innerArray.length, 0);