0

I need to get result after array loop is completed and do something with this result in Node Js project count and I need to check this variable after loop is completed

var count = 0;

myArray.forEach(element => {
    if(element == 'something'){
          count++;
    }
});


if(count == 2){
    // do smth
    }else if(count == 1){
        // do something else
    }else{
        // or do this
    }

currently if statement is being implemented before I get result from loop.

  • 3
    [Array.forEach is not asynchronous](https://stackoverflow.com/questions/5050265/javascript-node-js-is-array-foreach-asynchronous) – Zenoo Mar 16 '18 at 13:32
  • You can shorten it as `var count = myArray.filter( s => s == "something")` – gurvinder372 Mar 16 '18 at 13:33

2 Answers2

3

Unless you are doing an asynchronous operation in each iteration of forEach, you can shorten your code as

var count = myArray.filter(s => s == "something").length

Or something equivalent to

var f = str => str == "something"
var count = myArray.filter(f).length
rtn
  • 127,556
  • 20
  • 111
  • 121
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

The filter solution already provided is probably the best approach here! That said, here's some more background info:

The reason that the forEach is happening before the if block is because the forEach uses a callback, which is passed to Node's event loop to be executed later (I recommend doing some research on the event loop! Very helpful to know).

The most similar approach to yours that runs synchronously would be a standard for loop:

var count = 0;

for (var i = 0; i < myArray.length; i++) {
    if(element == 'something'){
          count++;
    }
});


if(count == 2){
    // Things
}
daniel.rigberg
  • 118
  • 1
  • 8