JavaScript rearrange array elements

Currently, I'm attempting to move the values of an array over by a random amount. For instance:

var array = [1,2,3,4];
var shiftAmount = 1;

The goal is to shift the array so that it looks like [4,1,2,3]

Answer №1

To reverse the split array, simply use slice and concat in the opposite order. Calculate the shift value using modulo to ensure it works for any number.
For a random number, utilize Math.random() and Math.round. Since Math.random() generates values between 0 and 1, multiply it by array length - 1 (as indexes start at 0 and go up to length -1).

function rearrangeArray(arr,shift) {
    shift = shift % array.length;
    return arr.slice(shift).concat(arr.slice(0,shift));
}

var array = [1,2,3,4];
let shift = Math.round(Math.random() * (array.length-1));
let result = rearrangeArray(array, shift);
console.log('Shifted by ' + shift + ': ',result.toString());

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

Employing the html.validationmessagefor to display a client-side error notification

My text fields have server-side validation messages. The field 'title' is a required field on the server side with a '[Required]' data attribute in the class, but it only seems to be checked on a postback or form submit. I am saving the ...

Can a repetitive 'setTimeout' function invocation ultimately cause the JS Engine to crash?

Imagine a scenario where I require data from the server every 10 seconds. A function would be created to fetch the data using AJAX, and then setTimeout would be used to schedule the function to run again: function RetrieveData(){ $.ajax({ url: " ...

Utilizing References in React Components

One of the challenges I am facing involves a Container that needs references to some of its child components: const Container = () => { const blocks: HTMLDivElement[] = []; return ( <div> <Navigation currentBlock={currentBlock} ...

The p-dialog lacks the proper styling and does not show or hide correctly

I am working on adding a feature where dragging and dropping an event in a calendar triggers a dialog box that requires the user to confirm if they want to postpone the event. However, I ran into an issue where the styling of my p-dialog is not defaulting ...

Ajax: The function assigned to the route does not get executed

Pressing a button triggers a confirmation box. If 'ok' is clicked, the div called 'EventData' should display the word 'reached'. The confirmation box appears when the button is clicked, but 'EventData' does not show ...

No content appearing on React screen

I initialized a fresh react project using "npx create-react-app name". After removing unnecessary files, the application no longer displays anything. I've encountered issues with react-router and defining routes as well. index.html: <!DOCTYPE html ...

Comparing two Objects in JavaScript results in automatic updates for the second Object when changes are made to the first

Can someone please assist me with a hash map issue I'm encountering in my for loop? When resetting the second object, it unintentionally alters the Map values of the previous Key in the Hash Map. Any guidance on how to prevent this behavior would be g ...

Display all pages in the DataTables plugin while utilizing responsive tables and additional features

I am struggling to combine the responsive and fixed header attributes of my current function with the "Show All" list feature, similar to what is demonstrated in this example: https://datatables.net/examples/advanced_init/length_menu.html I need assistanc ...

Pressing the enter key within Material UI Autocomplete will allow you to quickly create new

Wouldn't it be great if Autocomplete in material ui could do this: wertarbyte Imagine being able to insert text (string) without the need for a list of elements to select from. This means that the noOptions message shouldn't appear, and instead ...

Using Svelte to effectively connect to a specified object within an array

Check out this code snippet: <script> let data = [ {id: 1, first: "x"}, {id: 2, second: "y"} ]; </script> <input type="text" bind:value={data.first}/> If you modify the value in the input field and ...

How can we create responsive websites?

Since starting my Software Developer studies about 3 months ago, I've been working on a website project for a driving school with a team of four. The issue we're facing is that when we transfer and open files between laptops, the website layout a ...

Prevent overlapping of nodes and edges in a D3 force-directed layout

Check out this fascinating example at http://bl.ocks.org/mbostock/1747543: In the demonstration, Mike illustrates how to prevent nodes from colliding with each other in a graph. I'm curious if it's feasible to also prevent collisions between no ...

Discover the method to retrieve the month name from an HTML Date input value

Here we have a date input field <input id="customer-date" name="customer-date" type="date" required> Accompanied by this script const customerDate = document.getElementById('customer-date').value; const dateHandler = document.getElementB ...

Button to close Jquery Dialog

I've set up a custom alert UI using jQuery UI, but I'm having trouble getting the close button to work properly. Here's my code snippet where I'm trying to override the default alert() function with jQuery UI dialog as described in this ...

Retrieving information from a JSON object in Angular using a specific key

After receiving JSON data from the server, I currently have a variable public checkId: any = 54 How can I extract the data corresponding to ID = 54 from the provided JSON below? I am specifically looking to extract the values associated with KEY 54 " ...

Adjust the anchor tag content when a div is clicked

I have a list where each item is assigned a unique ID. I have written the HTML structure for a single item as follows: The structure looks like this: <div id='33496'> <div class='event_content'>..... <div>. ...

What is the best way to set a value for a variable within a UI component in React?

I'm still learning the ropes with React and JavaScript. My current challenge involves declaring a temporary variable and assigning the value of companyData.name to it, as I need to gather data from two variables like companyData.name. Below is my cod ...

Passing Props from _app.js to Page in ReactJS and NextJS

I recently made the switch from ReactJS to NextJS and am encountering some difficulties in passing props from _app.js to a page. My issue lies in trying to invoke a function in _app.js from another page. In ReactJS, this process was simple as you could cr ...

The relationship modelClass in ObjectionJS is undefined

I'm having an issue updating the relationship between a user and user_profile. Despite successfully updating the user, I encounter this error message when attempting to update the user_profile: ERROR: Error: UserProfile.relationMappings.user: modelCl ...

divs adjust their size based on how many are placed in a single row

I'm in the process of developing an online editing tool, and I'm interested to know if it's feasible to adjust the size of a <div> based on the number of visible div elements. For instance, I have a row with three columns, each set at ...