How to divide array into two arrays depending on condition?

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error How to divide array into two arrays depending on condition? on this date .

I’m trying to divide one array into two depending on a condition, i have an array that i have already filtered and i’m doing a forEach to loop trough it:

pending.forEach((items) => {

That console.log, prints this:

{year:2020, month:3, dates:[null, null, null, null, "01-01-2020", null]}
{year:2020, month:12, dates:[null, null, "10-03-2020", null, "01-01-2020", null]}

What i need to do is separate every item in two, to have one array with the dates that are null, and the other one with the dates that are different from null and maybe add a state, so in this case, i should have 2 arrays on the first item:

{year:2020, month:3, dates:[null, null, null, null, null]}, 
   {year:2020, month:3, dates:[ "01-01-2020"]}

But i don’t know how to access the dates, to then ask if the date is null or not.

Can anyone help me with this?


first create a copy of the object and then with the filter javascript function for arrays, you can pass the testing function which will return the elements that comply.

Like this:

const mynullObj = {...myobj }
    mynullObj.dates = myobj.dates.filter((date)=> date===null)
    myobj.dates = myobj.dates.filter((date)=> date!==null)


so the filter I propposed has some caveats when used inside the forEach or map, it will modify your original array so you must make a hardcopy of the array to split it. This function below will return two objects, one with the nulls and one with the dates.

const separatenulls = (pending) => {
  const pendingCopy = JSON.parse(JSON.stringify(pending));
  const notNull = => {
    item.dates = item.dates.filter((date) => date !== null);
    return item;
  const thesearenull =>{
     itemc.dates = itemc.dates.filter((date)=> date===null);
     console.log("itemc", itemc)
     return itemc
  return [notNull, thesearenull];

const [withdates, withnulls] = separatenulls(pending);