I have an array of objects. I need to get the object type (\"shape\" in this example) of the last object, remove it, and then find the index of the previous object in the ar
by using lodash library
You can find the last logical element.
_.findLast([1,2,3,5,4], (n) => {
return n % 2 == 1;
});
output: 5
While the currently accepted answer will do the trick, the arrival of ES6 (ECMA2015) added the spread operator which makes it easy to duplicate your array (this will work fine for the fruit
array in your example but beware of nested arrays). You could also make use of the fact that the pop method returns the removed element to make your code more concise. Hence you could achieve the desired result with the following 2 lines of code
const currentShape = fruits.pop().shape;
const previousInShapeType = [...fruits].reverse().find(
fruit => fruit.shape === currentShape
);
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/