Get last 2 elements of an array in a selector (Redux)

大城市里の小女人 提交于 2020-02-08 09:27:25

问题


An array starts as [] and then keeps growing with numbers being added to it.

I'm trying to create a selector to extract the last 2 elements of the array.

I've got the following:

const getHistory = (state) => state.score.history;

export const lastTwo = createSelector(
  [getHistory],
  history => (history.length > 1 ? history.slice(-1, -3) : 0)
);

It shows the initial 0 but then it does not output any value. Please advise. If, just for testing purposes, I do:

export const lastTwo = createSelector(
      [getHistory],
      history => history
    );

It outputs the array elements correctly as they are being added.

EDIT:

Based on the answer below, the answer is:

export const lastTwo = createSelector(
          [getHistory],
          history => history.slice(-2)
        );

回答1:


You can use negative begin index to slice from the end. Docs.

A negative index can be used, indicating an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence.

['zero', 'one', 'two', 'three'].slice(-2)
//["two", "three"]


来源:https://stackoverflow.com/questions/43430006/get-last-2-elements-of-an-array-in-a-selector-redux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!