Home > Software design >  How to split date strings in JavaScript array
How to split date strings in JavaScript array

Time:05-16

For the following Month/Day/Year datestring array...

const array1 = ["05/31/2022", "06/01/2022", "06/02/2022"]

...I am attempting to configure the array to slice and remove all datestring array items (starting with 01 as Day) if they follow after datestring array items with 31 as Day. Same goes for instances of Day 30 followed by Day 01.

To handle this, I set up a for statement to loop through all of the strings in the array. I then used a split method to remove "/" from each array item, thus breaking MM,DD,YYYY into separate variables.

for (let i = 0; i < array1.length; i  ) {
  var [month, day, year] = array1[i].split('/');
  console.log(month, day, year)
}

My intention for the next step is to set up a conditional that checks if an array item that includes 30 or 31 as "day" is followed by an array item that includes 01 as "day", then use slice to remove subsequent dates faster 30th or 31st. For this part, I attempted to re-consolidate month, day and year into individual array items, like so:

const newArray = []

for (let i = 0; i < array1.length; i  ) {
  var [month, day, year] = array1[i].split('/');
  newArray.push(month   day   year)
  console.log(newArray)
}

with output:

 ['05312022', '06012022', '06022022']

However, I'm not sure how to set up a conditional that checks if an array item that includes 30 or 31 as "day" is followed by an array item that includes 01 as "day". How can I go about the functionality for such a check?

CodePudding user response:

You can loop over the dates array and grab the currDay and prevDay and if the condition is satisfied, slice the dates array and return it.

const solution = (dates) => {
  for (let i = 1; i < dates.length; i  ) {
    const currDay = dates[i].slice(3, 5);
    const prevDay = dates[i - 1].slice(3, 5);
    if ((currDay === "01") & (prevDay === "31" || prevDay === "30")) {
      return dates.slice(0, i);
    }
  }
  return dates;
};

console.log(solution(["05/31/2022", "06/01/2022", "06/02/2022"]));

CodePudding user response:

The following us es Array#reduce to

  • retain all elements unless
  • the number of elements retained equals the index being considered and the current element has date 01 and follows a 30 or a 31
  • if index in consideration is greater than the number of items retained, meaning at least one element has been skipped, then the current element is skipped as well.

const array1 = ["05/31/2022", "06/01/2022", "06/02/2022"],

      output = array1.reduce(
          (prev,cur,i) => 
          prev.length && ["30","31"].includes( prev.slice(-1)[0].slice(3,5) ) && 
          (prev.length === i && cur.slice(3,5) === "01" || i > prev.length) ?
              prev :
              [...prev, cur],
          []
      );
      
console.log( output );

  • Related