Search code examples
javascriptarraysobjectarray-filter

JS Filter function to remove items in array between two ID's in object


I have a start ID, an end ID and an array of objects like this:

var items = [
    {"id":1590464645},
    {"id":1588963781},
    {"id":1587985477},
    {"id":1587986221},
    {"id":1625467428}
],
start_id = 1588963781,
end_id = 1587986221;

I would like to filter the array so the id in the array that matches the start_id, the id that matches the end_id and all elements in between are removed from the array. In this example only the first and last elements should remain in the filtered array.

items = items.filter(function (el) {
  // filter array
});

Solution

  • You'll need a variable outside of the filter() function to keep track of whether or not you're "in" the unwanted group:

    var items = [
          {"id" : 1590464645},
          {"id" : 1588963781},
          {"id" : 1587985477},
          {"id" : 1587986221},
          {"id" : 1625467428}
        ],
        start_id = 1588963781,
        end_id = 1587986221,
        inBetween = false;
     
    items = items.filter(function (el) {
      if (el.id == start_id)
        {
          inBetween = true;
          return false;
        }
      else if (el.id == end_id)
        {
          inBetween = false;
          return false;
        }
      else
        return ! inBetween;
    });
    
    console.log(items);