Find last matching object in array of objects

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

    by using lodash library

    You can find the last logical element.

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

    output: 5

    0 讨论(0)
  • 2020-12-06 04:57

    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
    );
    
    0 讨论(0)
  • 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/

    0 讨论(0)
提交回复
热议问题