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

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

I need to get an array having all the months between 'aug' and 'oct' and these two also based on year array.

Expected output: var newArr = ["aug", "sept", "oct"];

If var monthsRange = ["aug", "sept"]; then Expected output: var newArr = ["aug", "sept"];

If var monthsRange = ["aug"]; then Expected output: var newArr = ["aug"];

1
  • 1
    what about ["oct", "aug"]? Commented Jan 22, 2017 at 9:25

3 Answers 3

3

Use Array#slice method with Array#indexOf method.

year.slice(year.indexOf(monthsRange[0]), year.indexOf(monthsRange[1]) + 1)

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

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

function getMonths(r, y) {
  return r.length > 1 ? y.slice(y.indexOf(r[0]), y.indexOf(r[1]) + 1) : r;
}

console.log(getMonths(monthsRange, year));
console.log(getMonths(["aug"], year));

Sign up to request clarification or add additional context in comments.

Comments

0

How about the following way? If you want to try a little different way.

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

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

function checkMonth(month) {
    return year.indexOf(month) >= year.indexOf(monthsRange[0]) && year.indexOf(month) <= year.indexOf(monthsRange[1]);
}

console.log(year.filter(checkMonth));

Comments

0

Thisp proposal works for monthsRange = ["sep", "feb"] as well.

function getMonths(range) {
    var year = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'],
        start = year.indexOf(range[0]),
        end = year.indexOf(range[1] || range[0]);

    if (start <= end) {
        return year.slice(start, end + 1);
    } else {
        return year.slice(start).concat(year.slice(0, end + 1));
    }
}

console.log(getMonths(["sep", "feb"]));
console.log(getMonths(["mar"]));
console.log(getMonths(["may", "oct"]));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.