user4609276
user4609276

Reputation:

A shorter/cleaner way to add item to beginning of array, while also removing the last?

I added pagination to a project I'm working on, which uses React and Redux.

When I create a new item, I want it appended to the current list, while also removing the last item in the list; as each page has a limit to how many items to display.

The solution I came up with is something like this.

Basically, I want to add 1 to the array, but also remove 3; so the new array will be [1,2].

EDIT: sorry, but if this was a redux reducer, where I have to do everything in one line, how would I accomplish that?

const add = 1;
const state = [2,3];

const update = [add, ...state.filter((num, idx) =>{
  return idx !== state.length - 1
})]

reducer sample:

return {
   ...state,
   items: [add, ...state.filter((num, idx) =>{
      return idx !== state.length - 1
    })]
}

I might be overthinking it, and I have a feeling there is a much much cleaner way to write this..

What I also don't like is that I'm not even using the first argument in filter. It's just there so I can access the index..

Upvotes: 2

Views: 181

Answers (2)

charlietfl
charlietfl

Reputation: 171690

You can use slice(). The negative ending index works backwards from end of array

const add = 1;
const state = [2,3]

const res = [add, ...state.slice(0,-1)]
console.log(res)

Upvotes: 3

phi-rakib
phi-rakib

Reputation: 3302

To remove the last element of an array use array pop method and to add an element to first position use array unshift method.

const add = 1;
const state = [2, 3];

state.pop();
state.unshift(add);

console.log(state);

Upvotes: 1

Related Questions