【问题标题】:get last 6 items from array js after original array has been filtered过滤原始数组后从数组 js 中获取最后 6 项
【发布时间】:2019-07-08 15:02:27
【问题描述】:

我有一个数组,目前它会从数组中获取前 6 个项目,经过过滤后仅包含今天的游戏。

fixtures.filter(fixture => {
    return fixture.date === today;
}).slice(0, 6);

这很好用,但我想在过滤后从数组中获取最后 6 个项目。我尝试了以下方法,但对我不起作用。

fixtures.filter((fixture, index, arr) => {
    return fixture.date === today;
}).slice(Math.max(arr.length - 6, 1));

这是说arr 是未定义的。有没有办法在一个链中做到这一点?

【问题讨论】:

    标签: javascript arrays reactjs ecmascript-6


    【解决方案1】:

    您可以使用.slice(-6) 来获取数组的最后6 个元素。 A negative index can be used, indicating an offset from the end of the sequence.

    fixtures.filter(fixture => {
        return fixture.date === today;
    }).slice(-6);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-04
      • 1970-01-01
      • 2018-06-03
      • 2011-03-14
      • 1970-01-01
      • 1970-01-01
      • 2012-08-22
      相关资源
      最近更新 更多