Trí Phan
Trí Phan

Reputation: 1193

Performance: Use if in forEach or use filter then forEach the filtered array

I'm having an item array and I want to perform some tasks on the items which are satisfied some requirements. There are two approaches that can get this done.

First, use if clause in forEach

arr.forEach(item => {
  if (isSatisfied(item)) {
    //...do some tasks
  }
}

Second, filter the array then use forEach with the filtered one.

arr.filter(item => isSatisfied(item)).forEach(item => { /* do some tasks */ });

The isSatisfied will check the item if it meets the condition.

Which one will give me a better performance and why? Thank you for your help.

Upvotes: 1

Views: 913

Answers (1)

osekmedia
osekmedia

Reputation: 683

The first one would be more efficient because the second one is looping through some of the items twice.

Upvotes: 3

Related Questions