在原始数组被过滤后,从数组js中获取最后6个项目

问题描述 投票:1回答:1

我有一个数组,目前它已被过滤到仅包括今天的游戏后,从阵列中获得前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个回答
2
投票

您可以使用.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);
© www.soinside.com 2019 - 2024. All rights reserved.