Get range of months from array based on another array JavaScript


Suppose we have two arrays of strings. The first array contains exactly 12 strings, one for each month of the year like this −

const year = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];

The second array, contains exactly two strings, denoting a range of months like this −

const monthsRange = ["aug", "oct"];

We are required to write a JavaScript function that takes in two such arrays. Then the function should pick all the months from the first array that falls in the range specified by the second range arrays.

Like for the above arrays, the output should be −

const output = ['aug', 'sep'];

Note that we omitted the closing element of the range ('oct') in the output, its a part of the functionality.

Example

const year = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec']; const range = ['aug', 'dec'];
const getMonthsInRange = (year, range) => {
   const start = year.indexOf(range[0]);
   const end = year.indexOf(range[1] || range[0]);
   // also works if the range is reversed if (start <= end) {
         return year.slice(start, end);
   }
   else {
      return year.slice(start).concat(year.slice(0, end));
   };
   return false;
};
console.log(getMonthsInRange(year, range));

Output

And the output in the console will be −

[ 'aug', 'sep', 'oct', 'nov' ]

Updated on: 23-Nov-2020

299 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements