I wonder why lots of people would like to always avoid loops nowadays. They are just as natural structures as ifs and pure sequence of code lines. To avoid repeating yourself, write a function for it, what you even could add to Array.prototype. The following is a simple example, not tested, just for the idea.
For getting the index
Array.prototype.lastIndex = function(cond) {
if (!this.length) return -1;
if (!cond) return this.length-1;
for (var i=this.length-1; i>=0; --i) {
if (cond(this[i])) return i;
}
return -1;
}
Or for elements directly
Array.prototype.lastOrDefault = function(cond, defaultValue) {
if (!this.length) return defaultValue;
if (!cond) return this[this.length-1];
for (var i=this.length-1; i>=0; --i) {
if (cond(this[i])) return this[i];
}
return defaultValue;
}
Usage example:
myArr = [1,2,3,4,5];
var ind1 = myArr.lastIndex(function(e) { return e < 3; });
var num2 = myArr.lastOrDefault(function(e) { return e < 3; });
var num8 = myArr.lastOrDefault(function(e) { return e > 6; }, /* explicit default */ 8);
[{'a': something, 'b':12}, {'a': something, 'b':12}]