VIJAYABAL DHANAPAL
VIJAYABAL DHANAPAL

Reputation: 564

Rotate array and store all combination in object variable

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

Upvotes: 5

Views: 168

Answers (2)

Oghli
Oghli

Reputation: 2341

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: enter image description here

Upvotes: 1

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48417

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

Upvotes: 2

Related Questions