solanki...
solanki...

Reputation: 5098

Get range of elements from array based on another array

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"];

Upvotes: 2

Views: 280

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386550

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"]));

Upvotes: 0

VHS
VHS

Reputation: 10174

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));

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115212

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));

Upvotes: 3

Related Questions