Find last matching object in array of objects

前端 未结 9 791
我寻月下人不归
我寻月下人不归 2020-12-06 04:06

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

9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-06 04:50

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

提交回复
热议问题