Home > Software engineering >  How to push elements in array based on the avilability
How to push elements in array based on the avilability

Time:08-15

I have an array

let availabilityArray = [currentYearAvailability, previousYearAvailability, previousLastYearAvailability]
console.log(availabilityArray)

when I Console, I can able to find what is available what is not available

const preAuthAvailabilityYears =
    [
      currentYearAvailability ? currentYear : undefined,
      previousYearAvailability ? previousYear : undefined,
      previousLastYearAvailability ? previousLastYear : undefined,
    ]

Console

I need only the availability years to be displayed in the array instead showing as undefined as third argument, If it is undefined i shouldnot should in array

CodePudding user response:

const preAuthAvailabilityYears =
    [
      currentYearAvailability ? currentYear : undefined,
      previousYearAvailability ? previousYear : undefined,
      previousLastYearAvailability ? previousLastYear : undefined,
    ].filter(Boolean)

CodePudding user response:

You can filter it out like that if you are not required undefined.

Option 1

const preAuthAvailabilityYears =
    [
      currentYearAvailability ? currentYear : undefined,
      previousYearAvailability ? previousYear : undefined,
      previousLastYearAvailability ? previousLastYear : undefined,
    ].filter(Boolean);

Option 2

const preAuthAvailabilityYears =
        [
          currentYearAvailability ? currentYear : undefined,
          previousYearAvailability ? previousYear : undefined,
          previousLastYearAvailability ? previousLastYear : undefined,
        ].filter( item => item);
  • Related