2

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

5
  • Welcome 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! Commented Dec 19, 2017 at 11:13
  • 1
    use dataary[0].length. 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. 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.com/questions/12502843/… Commented Dec 19, 2017 at 11:17
  • 1
    But i need the count as 5 You need to get answer as 5 or 15? Commented Dec 19, 2017 at 11:17

3 Answers 3

3

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;
});
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

I would do it that way...

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.