JS Filter函数用于删除对象中两个ID之间的数组中的项目

时间:2015-11-05 21:43:30

标签: javascript arrays object array-filter

我有一个起始ID,一个结束ID和一个像这样的对象数组:

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

我想过滤数组,以便数组中的idstart_id匹配,idend_id相匹配,其中所有元素都会被删除从阵列。在此示例中,只有第一个和最后一个元素应保留在已过滤的数组中。

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

2 个答案:

答案 0 :(得分:2)

您需要在filter()功能之外的变量来跟踪您是否“进入”不受欢迎的群组:

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

答案 1 :(得分:0)

您可以尝试切片直至start_id,从end_id切换到数组末尾



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

var pureIds = items.map(function(item) {
  return item.id;
});

var result =
  items
  .slice(0, pureIds.indexOf(start_id))
  .concat(items.slice(pureIds.indexOf(end_id) + 1, pureIds.length));

console.log(result);