how do you check if an item is the last element to fulfil a certain condition inside a loop?

You can simulate a map + filter using reduce to do this:

var data = [{foo : 'bar'}, {foo : false}, {foo : 'bar'}, {foo : false}];

var elems = data.reduce(function(filtered, obj, index) {
  if (obj.foo === 'bar') {
     filtered.push(index);
  }
  return filtered;
}, []);

var last_index = elems[elems.length - 1];

data.forEach((value, index) => {
  if (value.foo === 'bar') {
    //do something
    //if this is the last which has a foo which is === bar then do something
    if (index === last_index) {
      // do the thing
      console.log('last: ', value, index);
    }
  }
});

Or, you can work with data backwards, and use a boolean to detect whether you have seen the last element or not:

var data = [{foo : 'bar'}, {foo : false}, {foo : 'bar'}, {foo : false}];

var last = true;

$.each(data.reverse(), function(key, value) {
  if (value.foo === 'bar') {
    //do something
    //if this is the last which has a foo which is === bar then do something
    if (last) {
      // do the thing
      console.log('last: ', value, data.length - key - 1);
      last = false;
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top