I am fetching some data from Mongodb. THe data is an array of objects. I would like to make the object with group.title === "unsubscribers" the last object in the array always. the array will always have variable length.
I am using React with Redux and trying to push my object with title "unsubscribers" to the end of the array so I can always render as last item in a table
Here is my reducer. the console.log is showing me 3 not the array of objects
import { LIST_GROUPS, LIST_SHOW_GROUPS } from '../actions/types';
export default function (state = [], action) {
switch (action.type) {
// when we logout, this action.payload is an empty string so lets do || false
case LIST_GROUPS:
const unSubGroup = action.payload.filter((group) => group.title === "unsubscribers")
const allOtherGroups = action.payload.filter((group) => group.title !== "unsubscribers")[0]
console.log(allOtherGroups.push(unSubGroup))
return action.payload
case LIST_SHOW_GROUPS:
return action.payload.filter((el) => { return !el.hide })
default:
return state;
}
}
2
Answers
Yes my code was ALMOST CORRECT. I needed to add the brackets to unSubGroup to make sure and return the object instead of an array with an. object inside.
I was getting a result like this where the unSubGroup was an array with an object, I only wanted the object.
above function gave me below output ( needed to add the [0] to end of unSubGroup filter method
Your code is correct, but
.push
returns the number of elements in the result, instead of the actual result, all you have to do is move theconsole.log
one line down:However, I think you should
return allOtherGroups
instead ofreturn action.payload