Find last matching object in array of objects

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 array that has the same type, e.g. "shape".

var fruits = [
    { 
        shape: round,
        name: orange
    },
    { 
        shape: round,
        name: apple
    },
    { 
        shape: oblong,
        name: zucchini
    },
    { 
        shape: oblong,
        name: banana
    },
    { 
        shape: round,
        name: grapefruit
    }
]

// What's the shape of the last fruit
var currentShape =  fruits[fruits.length-1].shape;

// Remove last fruit
fruits.pop(); // grapefruit removed

// Find the index of the last round fruit
var previousInShapeType = fruits.lastIndexOf(currentShape);
    // should find apple, index = 1

So, obviously the type in this example will be "round". But I'm not looking for an array value of "round". I'm looking for where fruits.shape = round.

var previousInShapeType = fruits.lastIndexOf(fruits.shape = currentShape);

But just using that doesn't work. I'm sure I'm missing something simple. How do I find the last item in the array where the shape of the object = round?

Answers:

Answer
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/

Answer
var fruit = fruits.slice().reverse().find(fruit => fruit.shape === currentShape);
Answer

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);
Answer

by using lodash library

You can find the last logical element.

_.findLast([1,2,3,5,4], (n) => {
  return n % 2 == 1;
});

output: 5

Answer

plain JS:

var len = fruits.length, prev = false;
while(!prev && len--){
    (fruits[len].shape == currentShape) && (prev = fruits[len]);
}

lodash:

_.findLast(fruits, 'shape', currentShape);
Answer

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
);
Answer

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];
Answer

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

Answer

This is a solution that does not depend on reverse, and therefore does not require "cloning" the original collection.

const fruit = fruits.reduce((acc, fruit, index) => (
    fruit.shape === currentShape ? index : acc
), 0);

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.