How to get sequence number in loops with JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

To get sequence number in loops, use the forEach() loop. Following is the code −

Example

let studentDetails =
[
   {
      id: 101, details: [{name: 'John'}, {name: 'David'},{name: 'Bob'}]},
      {id:102, details: [{name:'Carol'},{name:'David'},
      {name:'Mike'}]
   }
];
var counter = 1;
studentDetails.forEach(function(k){
   k.details.forEach(function(f) {
         console.log(counter++);
      }
   );
});

To run the above program, you need to use the following command −

node fileName.js.

Output

Here, my file name is demo159.js. This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo159.js
1
2
3
4
5
6
raja
Updated on 12-Sep-2020 07:46:59

Advertisements