add solution to redux remove item from array (#35593)
This commit is contained in:
committed by
The Coding Aviator
parent
719227b733
commit
1d77711431
@@ -3,8 +3,32 @@ title: Remove an Item from an Array
|
||||
---
|
||||
## Remove an Item from an Array
|
||||
|
||||
This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/certifications/front-end-libraries/redux/remove-an-item-from-an-array/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
|
||||
### Solution
|
||||
```javascript
|
||||
const immutableReducer = (state = [0,1,2,3,4,5], action) => {
|
||||
switch(action.type) {
|
||||
case 'REMOVE_ITEM':
|
||||
// don't mutate state here or the tests will fail
|
||||
return [...state.slice(0, action.index), ...state.slice(action.index + 1, state.length)];
|
||||
// or return state.slice(0, action.index).concat(state.slice(action.index + 1, state.length));
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
};
|
||||
|
||||
<a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
|
||||
const removeItem = (index) => {
|
||||
return {
|
||||
type: 'REMOVE_ITEM',
|
||||
index
|
||||
}
|
||||
}
|
||||
|
||||
<!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
|
||||
const store = Redux.createStore(immutableReducer);
|
||||
```
|
||||
|
||||
### Notes
|
||||
* array.slice(fromIndex, untilIndex) returns a new array
|
||||
* 1st slice from the first item's index (0 inclusive) until indexToRemove(action.index exclusive)
|
||||
* 2nd slice from item right after indexToRemove (action.index + 1 inclusive) until length (last item's index + 1 exclusive)
|
||||
* since slice returns a new array, combine both parts with [...array1, ...array2] spread operator
|
||||
* or combine them with .concat()
|
||||
|
Reference in New Issue
Block a user