1

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.

6
  • The question is a bit unclear, at least to me. Can you please edit your question and add the expected output? Commented Jun 1, 2019 at 17:15
  • 4
    Why not just add 1 to the month in 0-11 format? Commented Jun 1, 2019 at 17:15
  • cuase this I have a loop that generate this for 10 years Commented Jun 1, 2019 at 17:19
  • What does the duration have to do with anything? If you are just getting the month from 1 you literally just do b[i] + 1. Doesn't matter how many years its for? Commented Jun 1, 2019 at 17:20
  • 1
    XY problem Commented Jun 1, 2019 at 17:27

2 Answers 2

3

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

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

1 Comment

tnx but I need the opposite of this condition , sry if im not clear about that. console.log(getZeroBasedMonth(0)) >>> 1 and console.log(getZeroBasedMonth(11)) >>> 12
0

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

1 Comment

if you decide to go down this path, Javascript has a map function for this. There is no need to di it with for loops.

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.