I have month array which should be rotate left to right for its length time. Store all rotational array in object variable. Can you please suggest more efficient way to do it.
var Month = ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec"];
Output looks like:
monthRotate = {
rotate1: ["Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan"],
rotate2: ["Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec", "Jan", "Feb"],
.
.
.
.
rotate11: ["Dec", "Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov"];
}
I have tried this below method.
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var rotate = {};
for (var i=1;i<months.length;i++){
var mts = months.slice(i).concat(months.slice(0,i));
rotate["rotate"+i] = mts;
}
console.log(rotate);
You can use shift
method in order to remove the first element of the given array
and then push it at the end of the array.
var months = ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec"];
let final = [...Array(months.length-1)].reduce(function(arr){
months.push(months.shift());
arr.push([...months]);
return arr;
},[]);
console.log(final);
You can create rotations
array object in this way:
var Month = ["Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec"];
var rotations = [];
for(var i = 0; i < 11; i++){
rotations[i] = [];
for(var j = i+1, k = 0; k < 12; j++, k++){
if(j === 12){
j = 0;
}
rotations[i].push(month[j]);
}
}
Console output:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With