Babak Abadkheir
Babak Abadkheir

Reputation: 2350

array return index from another array

suppose we have this two array. in some condition, I want to return the index of a second array.

let a = [1, 2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10 ,11 , 12]
let b = [0, 1, 2, 3 , 4 , 5, 6 , 7 , 8, 9, 10, 11]

if (a[2]) ? return b[2] : return null

why I need this? because I have a month number of the year that starts from 0 to 11. but I need to turn this 1 12 for storing in my database. sry about the title of this question if someone has a better title I would be glad about changing it.

Upvotes: 1

Views: 56

Answers (2)

basic
basic

Reputation: 3408

Why make this harder than it needs to be? Just add 1 to the value you get from your initial array. Here is, per your comment, 10 years worth of values for the months with a +1 value.

let years = 10;
let months = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
let allYears = [];

for(let i = 0; i < years; i++){
    let year = [];
    for(let x = 0; x < months.length; x++){
        year[x] = months[x] + 1;
    }
    allYears.push(year);
}

console.log(allYears);

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386570

You could calculate the value by adding 11 and get the remainder value with 12.

function getZeroBasedMonth(n) {
    return (n + 11) % 12;
}

console.log(getZeroBasedMonth(1));
console.log(getZeroBasedMonth(12));

For the getting the opposite, just add one.

function getMonth(n) {
    return n + 1;
}

console.log(getMonth(0));
console.log(getMonth(11));

Upvotes: 3

Related Questions