Rotate the array and save all combinations in an object variable

I have an array of months that should turn left to right over its time. Store the entire rotating array in an object variable. Can you suggest a more efficient way to do this.

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 tried this method below.

 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); 
+5
source share
2 answers

You can use the shift method to remove the first element of a given array , and then click 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); 
+2
source

You can create a rotations array object 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: enter image description here

+1
source

Source: https://habr.com/ru/post/1273582/


All Articles