Alvin Moyo
Alvin Moyo

Reputation: 218

How to check if item is the last element to fulfil a certain condition inside a loop

let's say I have arbitrary data which looks like this

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

and I am looping through that data using JQUERY. How do I check if an iteration is the last to fulfil a certain condition, for example;

$.each(data, function(key, value){


    if (value.foo===bar) {
        //do something
        // if this is the last which has a foo which is === bar then do something
    }

});

Upvotes: 0

Views: 1579

Answers (3)

Djaouad
Djaouad

Reputation: 22776

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>

Upvotes: 1

Andreas
Andreas

Reputation: 21881

Use a regular for loop and iterate in reverse order over your collection so the first match would be the last match in original order

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

for (let i = data.length - 1, found = false; i >= 0; i--) {
  if (!found && data[i].foo === 'bar') {
    console.log('"last" match at ', i);
    found = true;
  }
  
  // ...
}

Upvotes: 1

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

you can store the last foo which is equal to bar in a variable and do operation on it outside the loop.

See below sample code

var lastFooEqBar= null;
$.each(data.reverse(), function(key, value) {
    if (value.foo === bar) {
        //do something
        //store in variable
        lastFooEqBar = value;
    }
});
if(null!=lastFooEqBar) {
  //do operation on last foo equals to bar
}

Upvotes: 0

Related Questions