Find last matching object in array of objects

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

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

提交回复
热议问题