Cycle through an array a specified number of times while shifting elements

Imagine you have an array like [1,2,3,4,5], and you want to rotate it a total of 3 times. After the first rotation, the array should look like [2,3,4,5,1]. You need a solution that can handle rotating the array any number of times without manual intervention. Here's an attempt at creating a function to rotate the array:

function rotateLeft(arr, n) {
    var newArr = [];
         for( let i=1; i< arr.length; i++){
            newArr.push(arr[i]);
        }
            newArr.push(arr[0]);
        
    console.log(newArr);
}

rotateLeft([1,2,3,4,5], 3);

Answer №1

Rearrange the elements of an array by pushing the first element to the end using a while loop

const originalArray = [1,2,3,4,5];
console.log(`Original Array: [${
  originalArray}], Rearranged Array: [${
    rearrangeArray(originalArray, 3)}]`);

function rearrangeArray(array, times) {
  // if you want to mutate the original array
  // omit cloning
  const clonedArray = [...array];
  while (times--) {
    clonedArray.push(clonedArray.shift());
  };
  return clonedArray;
}

Answer №2

Instead of performing an in-place rotation of the array, a new array is created to achieve a simpler solution:

function rotateLeft(arr, n) {
  n %= arr.length;
  return [...arr.slice(n), ...arr.slice(0, n)];
}

// Generating an array filled with numbers
const arr = [...Array(20).keys()];

console.log(...arr);

// Rotating the array left by 8 positions
console.log(...rotateLeft(arr, 8));

// Rotating the array left by -22 positions (equivalent to rotating right by 22)
// Since the length of the array is 20
// This is the same as rotating left by -2 
// Which is equivalent to rotating left by 18 positions
console.log(...rotateLeft(arr, -22));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to create dynamic documents in Firestore using Angular?

How can I use a dynamic ID to fetch the values of a document in Firestore? For example, if I have documents named document1 and document2 under the same collection, how can I specify a dynamic path with a dynamic document name to retrieve the specific do ...

Having difficulty retaining the value of a variable following the retrieval of JSON data

For my current project, I am utilizing the highstocks charting library in combination with JQuery. My goal is to create a single chart divided into three sections, each displaying different data sets. To import the data, I have referenced the sample code p ...

what is the method for passing query string parameters in an XMLHttpRequest to a PHP page

I have a PHP variable named $name=$_POST["name"]; <script> pge = '<?php echo $name ;?>'; var url = "searchCustomerByNameApi2.php" //some code xmlhttp.open("GET", url + "?pge=" + pge, true); xmlhttp ...

Issue with displaying mysql row object as variable in pug view's javascript in Express.js manifests as 'undefined' output

Here is the index.js code snippet: app.get("/users", (req,res)=> { connection.query("SELECT Name, Currently_Watching FROM `user-data` ", function(error, rows, fields) { if (error) { res.send(error); } else { ...

Incomplete Json information

As I embark on my journey to learn Javascript and work on building an application simultaneously, I can't help but feel optimistic about the learning process. To guide me through this venture, I've turned to the teachings of Alex MacCaw in his bo ...

"Looking for a datetime picker plugin that works well with Bootstrap

Check out this efficient DateTimePicker example. <head> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script> <link rel="stylesh ...

Python function for sorting elements into arrays within bins

I have data points in arrays x, y, and v which I am binning on the x-y plane. After binning, I would like to retrieve the x, y, and v values for each bin as separate arrays. My current code achieves this but is not efficient for large datasets with numerou ...

Creating objects based on interfaces

After looking at this straightforward code: interface int1 { aa: string, bb: number, } const obj1:int1 = {} //#1 function fun(param_obj:int1) { //#2 } I am curious as to why the compiler throws an error: Type '{}' is missing the fol ...

Error: You cannot implement an import statement beyond a module while utilizing reactjs CDN Links

I am developing a Reactjs app using react CDN Links instead of 'npx create-react-app'. I have set up an index.html, index.js, and App.js files. My goal is to import the App.js component into the Index.js file using import App from '../compon ...

Customized content is delivered to every client in real-time through Meteor

I am currently working on creating a multiplayer snake game using three.js and meteor. So far, it allows one player to control one out of the three snakes available. However, there is an issue where players cannot see each other's movements on their s ...

In the Node environment, why does null evaluate as less than 3 while also being greater than 3?

How come null is false when compared to 3 in node, and true when compared to 3? $ node > null > 3 false > null < 3 true ...

Python's version of the Game of Life is not functioning correctly

I am facing an issue with my automata - Game of Life. I have an image that I convert to a 2D matrix. In the middle of this image, there is an oscillator. According to the rules, the output of this function should be another oscillator but turned by 90 degr ...

Invoking a function from a higher-level parent scope within multiple layers of nested directives

I am working with a data structure that is nested infinitely. There is a top-level object containing a collection of objects, and each of these objects can also have their own collection of objects. To iterate through this tree, I have implemented the fol ...

Ways to ensure ngModel is accessible across components

I've hit a wall and I'm starting to lose my mind. I've tried all the different methods like FormsModules, ReactiveForms, FORMDIRECTIVES, Input, Output, but I just can't seem to figure out how to make ngModel work between components. My ...

Creating unique border-radius for each point in a Highcharts column chart with React

Let's flip the script and start at the finish line. My goal is to customize my column chart to resemble this design: https://i.stack.imgur.com/FckJB.png Creating this style is a breeze with chart.js Credit: I've already delved into this inquiry ...

Gradually bringing a tag into view, gently fading it away, and then altering the text before beginning the cycle anew

I have a situation where an tag's content is being dynamically changed with jQuery and then faded in and out using the Velocity JS library along with the setInterval function. Initially, everything works smoothly for about 30 seconds. However, after ...

eliminating the hues beneath the lines on Morris region charts

I'm seeking advice on how to remove colors below the lines in Morris area charts. Any ideas? Here's the code snippet I've been using: Morris.Area({ element: 'area-example', data: [ { y: '2006', a: 100, b: 90 }, ...

Accessing the Selected Value in Javascript

Having encountered a problem with my JavaScript script, I need some assistance. I am relatively new to coding in JavaScript and generally try to avoid it due to the complexities of debugging. The issue at hand involves a script I am working on for AJAX tha ...

What is behind the peculiar reaction when checkboxes are used in React?

In this demo, what is causing the button to disable only after both checkboxes have been checked? Is the button not initially displayed as disabled due to the way state behaves in react? The example consists of two checkboxes: I have read and agree to te ...

Storing a portion of AJAX response as a PHP variable

Is there a way to store data received through an AJAX response in a PHP variable? I want to take the value of $('#attempts_taken').val(data[11]); and save it as a PHP variable. Any help would be great! <script type="text/javascript> $(do ...