Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
Filtering an array of objects into two new arrays and saving each to useState

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.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can do like this as below code

setAvailableUnits(data.filter((v)=> v.status === "AVAILABLE"));
setAssignedUnits(data.filter((v)=> v.status === "ASSIGNED"));
about 4 years ago · Juan Pablo Isaza Report

0

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"));
about 4 years ago · Juan Pablo Isaza Report

0

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);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!