Home > Software engineering >  Filtering an array of objects into two new arrays and saving each to useState
Filtering an array of objects into two new arrays and saving each to useState

Time:10-16

I have an array of objects

const units = [
   {id: 1, status: "AVAILABLE"}, 
   {id: 1, status: "ASSIGNED"},
   {...}
]

My goal is write a function that filters the array into two new arrays -- one array for objects that have status: "AVAILABLE" and another array for objects that have status: "ASSIGNED"

I'm setting state

const [availableUnits, setAvailableUnits] = useState([]);
const [assignedUnits, setAssignedUnits] = useState([]);

I want to filter through the units array and set each new array to its given state. I was trying do something like this:

setAvailableUnits(() => units.filter((unit) => {
     return unit.status === "AVAILABLE";
}))

This doesn't work though. I'd like one function that filters and sets state for both statuses.

Thank you.

CodePudding user response:

You can do like this as below code

setAvailableUnits(data.filter((v)=> v.status === "AVAILABLE"));
setAssignedUnits(data.filter((v)=> v.status === "ASSIGNED"));

CodePudding user response:

if units is already known before rendering the component you can try this

const [availableUnits, setAvailableUnits] = useState(units.filter((v)=> v.status === "AVAILABLE"));
const [assignedUnits, setAssignedUnits] = useState(units..filter((v)=> v.status === "ASSIGNED"));

if not and it comes from fetching for example

you can try

setAvailableUnits(data.filter((v)=> v.status === "AVAILABLE"));
setAssignedUnits(data.filter((v)=> v.status === "ASSIGNED"));

CodePudding user response:

This will only work if there are just two statuses available: AVAILABLE and ASSIGNED. Modify the if statement if you want to include more statuses.

const units = [
   {id: 1, status: "AVAILABLE"}, 
   {id: 1, status: "ASSIGNED"},
];

const newAvailableUnits = [];
const newAssignedUnits = [];

units.forEach((unit) => {
    if (unit.status === "AVAILABLE") newAvailableUnits.push(unit);
    else newAssignedUnits.push(unit);
})

setAvailableUnits(newAvailableUnits);
setAssignedUnits(newAssignedUnits);
  • Related