Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 915
VIJAYABAL DHANAPAL Avatar asked Oct 18 '22 02:10

VIJAYABAL DHANAPAL


2 Answers

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);
like image 80
Mihai Alexandru-Ionut Avatar answered Oct 21 '22 09:10

Mihai Alexandru-Ionut


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

like image 29
Oghli Avatar answered Oct 21 '22 08:10

Oghli