Reputation:
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
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
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