Reputation: 218
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
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
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
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