Alexander Solonik Alexander Solonik - 8 months ago 50
Javascript Question

How to return an element in a forEach loop

In my code i have an array that is like below:

localStroge_Procrastinator_tasks = [object , object, object]

Now i want to iterate over the array using a forEach loop and return when the id of an object matches the id i provide , let me lay out the code to make my example clear.

storeRelevantObj = localStroge_Procrastinator_tasks.forEach(function(e, i){
if (e.task_Id === task_Id) {
return e;

But wheni run the code even if the if conditon passes and e is returned ,
still remains empty , why ? why is the return statement not working ??

Answer Source

Don't use forEach() for filtering, use filter() instead:

var storeRelevantObj = localStroge_Procrastinator_tasks.filter(function(e) {
     return e.task_Id === task_Id;

If you don't mind IE support, you can use the find() method that is returning the first element that satisfies the condition (it's also more performant since it can return immediately upon first match):

var storeRelevantObj = localStroge_Procrastinator_tasks.find(function(e) {
     return e.task_Id === task_Id;

Also, if you're targeting ES6 or using a transpiler (like Babel), your predicate can be expressed using an Arrow Function:

var storeRelevantObj = localStroge_Procrastinator_tasks.find(e => e.task_Id === task_Id);