Search code examples
javascriptarraysreselect

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


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

Solution

  • 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"]