Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 748
Graeck Avatar asked Oct 21 '15 20:10

Graeck


3 Answers

var fruit = fruits.slice().reverse().find(fruit => fruit.shape === currentShape);
like image 181
Luke Liu Avatar answered Oct 17 '22 09:10

Luke Liu


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);
like image 32
Den Avatar answered Oct 17 '22 11:10

Den


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/

like image 25
AtheistP3ace Avatar answered Oct 17 '22 11:10

AtheistP3ace