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
You should use filter! filter takes a function as an argument, and returns a new array.
var roundFruits = fruits.filter(function(d) {
// d is each element of the original array
return d.shape == "round";
});
Now roundFruits will contain the elements of the original array for which the function returns true. Now if you want to know the original array indexes, never fear - you can use the function map. map also operates on an array, and takes a function which acts on the array. we can chain map and filter together as follows
var roundFruits = fruits.map(function(d, i) {
// d is each element, i is the index
d.i = i; // create index variable
return d;
}).filter(function(d) {
return d.shape == "round"
});
The resulting array will contain all objects in the original fruits array for which the shape is round, and their original index in the fruits array.
roundFruits = [
{
shape: round,
name: orange,
i: 0
},
{
shape: round,
name: apple,
i: 1
},
{
shape: round,
name: grapefruit
i: 4
}
]
Now you can do whatever you need to with the exact knowledge of the location of the relevant data.
// get last round element
fruits[4];
var fruit = fruits.slice().reverse().find(fruit => fruit.shape === currentShape);
I would suggest another nice solution which doesn't bother cloning a new object using reverse()
.
I use reduceRight
to does the job instead.
function findLastIndex(array, fn) {
if (!array) return -1;
if (!fn || typeof fn !== "function") throw `${fn} is not a function`;
return array.reduceRight((prev, currentValue, currentIndex) => {
if (prev > -1) return prev;
if (fn(currentValue, currentIndex)) return currentIndex;
return -1;
}, -1);
}
And usage
findLastIndex([1,2,3,4,5,6,7,5,4,2,1], (current, index) => current === 2); // return 9
findLastIndex([{id: 1},{id: 2},{id: 1}], (current, index) => current.id === 1); //return 2
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);
plain JS:
var len = fruits.length, prev = false;
while(!prev && len--){
(fruits[len].shape == currentShape) && (prev = fruits[len]);
}
lodash:
_.findLast(fruits, 'shape', currentShape);
This is a solution that does not depend on reverse
, and therefore does not require "cloning" the original collection.
const lastShapeIndex = fruits.reduce((acc, fruit, index) => (
fruit.shape === currentShape ? index : acc
), -1);