delv123
delv123

Reputation: 146

How to divide array into two arrays depending on condition?

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) => {
      console.log(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?

Upvotes: 0

Views: 616

Answers (1)

BlowFish
BlowFish

Reputation: 354

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)

EDIT:

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 = pending.map((item) => {
    item.dates = item.dates.filter((date) => date !== null);
    return item;
  });
  const thesearenull = pendingCopy.map((itemc)=>{
     itemc.dates = itemc.dates.filter((date)=> date===null);
     console.log("itemc", itemc)
     return itemc
    })
  return [notNull, thesearenull];
};

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

Upvotes: 1

Related Questions