Search code examples
javascriptarraysfilterforeachsplice

alternatives for this forEach


I have some code which loops through a user array using forEach. And within that loop i again use forEach to loop through their price alerts. It looks like this

  user_data.users.forEach((user, index) => {
    if (user.id == id) {
      user.price_alerts.forEach((alert, alert_index) => {
        if (alert.symbol == symbol) {
          //remove alert
          user.price_alerts.splice(alert_index, 1);
        }
      });
    }
  });

But the problem with this is instead of removing ALL the matches with the 'SYMBOL' it just removes one. How do i fix this ? Thanks in advance <3


Solution

  • If you need remove all elements which are not satisfying some condition, then try to use filter method:

    let result = user.price_alerts.filter(alert => alert.symbol !== symbol);
    

    UPDATE:

    user.price_alerts = user.price_alerts.filter(alert => alert.symbol !== symbol);