Find last matching object in array of objects
var previousInShapeType, index = fruits.length - 1;
for ( ; index >= 0; index--) {
if (fruits[index].shape == currentShape) {
previousInShapeType = fruits[index];
break;
}
}
You can also loop backwards through array.
Fiddle: http://jsfiddle.net/vonn9xhm/
You can transform your array to an array boolean
type and get the last true
index.
const lastIndex = fruits.map(fruit =>
fruit.shape === currentShape).lastIndexOf(true);
var fruit = fruits.slice().reverse().find(fruit => fruit.shape === currentShape);