2018-10-12 15:37:13 -04:00
|
|
|
---
|
|
|
|
title: Remove an Item from an Array
|
|
|
|
---
|
2019-07-24 00:59:27 -07:00
|
|
|
# Remove an Item from an Array
|
|
|
|
|
|
|
|
|
|
|
|
---
|
|
|
|
## Solutions
|
|
|
|
|
|
|
|
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
2018-10-12 15:37:13 -04:00
|
|
|
|
2019-05-16 02:31:37 -05:00
|
|
|
```javascript
|
2019-07-24 00:59:27 -07:00
|
|
|
const immutableReducer = (state = [0, 1, 2, 3, 4, 5], action) => {
|
|
|
|
switch (action.type) {
|
|
|
|
case "REMOVE_ITEM":
|
2019-05-16 02:31:37 -05:00
|
|
|
// don't mutate state here or the tests will fail
|
2019-07-24 00:59:27 -07:00
|
|
|
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));
|
2019-05-16 02:31:37 -05:00
|
|
|
default:
|
|
|
|
return state;
|
|
|
|
}
|
|
|
|
};
|
2018-10-12 15:37:13 -04:00
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
const removeItem = index => {
|
2019-05-16 02:31:37 -05:00
|
|
|
return {
|
2019-07-24 00:59:27 -07:00
|
|
|
type: "REMOVE_ITEM",
|
2019-05-16 02:31:37 -05:00
|
|
|
index
|
2019-07-24 00:59:27 -07:00
|
|
|
};
|
|
|
|
};
|
2018-10-12 15:37:13 -04:00
|
|
|
|
2019-05-16 02:31:37 -05:00
|
|
|
const store = Redux.createStore(immutableReducer);
|
|
|
|
```
|
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
#### Code Explanation
|
2019-05-16 02:31:37 -05:00
|
|
|
* 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()
|
2019-07-24 00:59:27 -07:00
|
|
|
</details>
|