Find last matching object in array of objects

前端 未结 9 785
我寻月下人不归
我寻月下人不归 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:58

    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/

提交回复
热议问题