TonyV
September 8, 2022, 6:52pm
1
I see the solution uses the spread operator and two slice operations. Is it possible to solve this with a filter sort of like what I am trying here.
**Your code so far**
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.filter(index => {
return state.index !== action.payload.index
});
default:
return state;
}
};
const removeItem = (index) => {
return {
type: 'REMOVE_ITEM',
index
}
}
const store = Redux.createStore(immutableReducer);
**Your browser information:**
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36
Challenge: Redux - Remove an Item from an Array
Link to the challenge:
lasjorg
September 8, 2022, 7:13pm
2
Yes, but not like that.
There is no index property on state
The first parameter for filter
is the element, not the index.
The action
does not have a payload
property.
const numbers = [1, 2, 3, 4, 5];
const filtered = numbers.filter((_, idx) => idx !== 0);
console.log(filtered); // [2, 3, 4, 5]
TonyV
September 8, 2022, 7:20pm
3
what about using the spread operator to sort of add a set of indices? Then you could pass any index in the action, couldn’t you.
lasjorg
September 8, 2022, 7:22pm
4
Not sure I understand what you mean. Can you post an example?
BTW I updated the solution thread with an example. But do try to do it yourself first.
TonyV
September 8, 2022, 7:34pm
5
The challenge also seems to suggest a solution using concat. Shouldn’t we be able to see a solution using concat?
lasjorg
September 8, 2022, 7:40pm
6
It does, it is the commented-out code in the first solution. The Code Explanation part also mentions it.
I guess it might be made into a separate example but I’m not sure if that is really needed.
TonyV
September 8, 2022, 7:49pm
7
What does the underscore represent in your solution?
TonyV
September 8, 2022, 7:54pm
8
By the way. Earlier, I meant that {…state} has a set of indices, but this is an object so maybe filter can not be used with it. Or can you?
lasjorg
September 8, 2022, 8:01pm
9
The filter method has a fixed parameter list (element, index, originalArray).
The index is in the second parameter list position and we have to have the first parameter to get the correct value for the second. As we do not need the element we can signify this by using an underscore _
.
You can use whatever you like but _
is the convention for unused variables.
Sorry I still do not know what you mean.
system
Closed
March 10, 2023, 8:02am
10
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.