Rearranging an array using JavaScript

Looking to rearrange an array in a specific order:

Starting with the initial array:

const weekDaysArray = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'];
containing the days of the week in sequence, then obtaining a variable

const firstWeekday = Object.values(formattedReadsByDay)[0].dayOfWeek;
which holds a day of the week, let's say We for this example.

When it returns We, I want to change the array to:

weekDaysArray = ['We', 'Th', 'Fr', 'Sa', 'Su', 'Mo', 'Tu'];

I attempted

weekDaysArray [...weekDays.slice(-1), ...weekDays.slice(0, -1)]
but it didn't yield the desired result. Any suggestions?

Answer №1

To proceed, follow these steps:

  1. Determine the index of the first day.
  2. Extract the portion of the array starting from the first day (inclusive) to the end. This becomes the new beginning of the week.
  3. Retrieve the segment of the array starting from the beginning up to the first day (excluding it). This forms the new end of the week.
  4. Combine both parts together.

These operations can be executed as shown below:

const weekDaysArray = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'];

const firstWeekday = "We";

//1. Find the index
const index = weekDaysArray.indexOf(firstWeekday);

//2. Obtain the start of the week
const startWeek = weekDaysArray.slice(index);
//3. Acquire the end of the week
const endWeek = weekDaysArray.slice(0, index);

//4. Merge the new week together
const result = [...startWeek, ...endWeek];

console.log(result);

Answer №2

To reorganize the array by moving the first item to the end, you can use the code snippet

weekDaysArray.push(weekDaysArray.shift())
. This operation transforms an array like [1, 2, 3] into [2, 3, 1]. Afterwards, check if the first element in the array matches your desired day with weekDaysArray[0] == your day. If it does, return the modified array. If not, repeat the same operation one more time.

Answer №3

Here's a possible implementation based on the response provided by Dima Vak:

function organizeWeekdays (initialDay) {
    const daysOfWeek = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'];

    for(let i = 0; i < daysOfWeek.length; i++) {
        if (daysOfWeek[0] === initialDay) break;
        daysOfWeek.push(daysOfWeek.shift())
    }

    return daysOfWeek;
}

const startingDay = Object.values(formattedReadsByDay)[0].dayOfWeek;
console.log({
    result: organizeWeekdays(startingDay)
});

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

Unable to divide the JavaScript AJAX outcome into separate parts

Working with JavaScript, I have received the following object from an Ajax response: {"readyState":4,"responseText":"\r\nsuccess","status":200,"statusText":"OK"} Within my code block, I am attempting to extract the responseText from this object ...

Tips for extracting information from Firebase and showing it on a Google gauge chart

I'm having some trouble displaying data from Firebase on a gauge chart. I keep getting an error that says "Uncaught (in promise)". Here's the JavaScript code I've been working with: <script type="text/JavaScript"> google.ch ...

Utilizing unique symbols to dynamically add form elements to an HTML page with jQuery's append method

I am facing an issue with creating forms on my HTML page. Here is an example of how I am trying to do it: <form action="/tasks/<%= allTasks.e[0].id %>/delete" method="POST"> <button class="deleteTask">Delete</button> </f ...

Implementing a JavaScript validator for an ASP textbox

I have come across many posts discussing how to prevent an ASP textbox from accepting only numbers. However, I am looking for a JavaScript example that can check if the entered value falls between 0 and 100. My validator currently checks if each key entere ...

Retrieving the necessary key values from a JSON dictionary

I'm attempting to retrieve keys from a dictionary using JavaScript. The user uploads a .json file containing the dictionary, and I want to display the keys from that uploaded dictionary. It's important to note that only .json dictionaries can be ...

Is it possible to allow null values for a Sequelize foreign key?

Is it possible to allow null values for a foreign key in Sequelize? The scenario involves a 'through' and 'belongsToMany' association: Shelf belongsToMany(Book, { through: Library, as: "Books"}); Book belongsToMany(Shelf, { th ...

Discovering how to navigate to a link within a web table using Cypress has been a challenge, as I keep receiving the error message stating that the element is not visible due to its CSS property being

Trying to click on the first enabled link in the 'Action' column of a web table has been proving difficult. In the example given, the first two rows do not have an enabled link, so the goal is to click on '8.5 AccountH' https://i.stack ...

How can I execute a StoredProcedure using JavaScript?

I have a form with an email field and label <asp:TableRow runat="server"> <asp:TableCell runat="server"> <asp:TextBox runat="server" ID="txtUserEmail" onfocusout="emailVerification()" CssClass="forTe ...

`Where to include controller.js scripts in an Angular application`

As I dive into learning angular.js with .NET MVC, one major issue that keeps coming up is the fact that many tutorials advise referencing multiple controllers and services in the main (_Layout) page, which can make it quite messy. Although it may seem sim ...

How can I specify which node_modules to include when using electron-packager in Electron?

I am in the process of packaging my electron app, and it specifically requires the mqtt and node-notifier modules. What I want to do is exclude all node_modules except for these two modules. Let's say I want to exclude the following files from packag ...

conceal parent window element upon clicking an image within an iframe

I'm facing a challenge with hiding certain buttons in a parent window when opening a modal by clicking an image inside an iframe. Below is the code snippet that I am using: In the parent window - <iframe id="gallery" src="links/gallery.html" wid ...

Utilizing JSON data to generate an HTML webpage showcasing a collection of community districts through the power of JavaScript

As a beginner in javascript, I am working with a JSON file that contains an array of objects. Each object includes two properties: a borough and mappings. Mappings have two sub-properties called macro and neighborhoods. The macro represents a larger neighb ...

The function WebGLRenderer() from three.js allows for rendering in

When initializing the WebGLRenderer, I am passing in a canvas DOM element like shown below: var jqc = $('#myCanvas'); //accessing canvas with jQuery; var par = {canvas:jqc.get()}; //creating parameter object with canvas DOM element var renderer ...

Monitoring the loading progress of multiple files using Three JS

Just starting out with Three JS and I'm on a mission to create a loading screen that displays the progress of assets being loaded for a scene. I have a total of 7 different types of assets, including: 4 GLB files 2 Texture files And 1 Obj file Acco ...

What are the steps to effectively utilize an interface within a TypeScript file that contains its own internal import?

Currently, I am in the process of developing a React JavaScript project using WebStorm and attempting to enable type hinting for our IDEs (including VS Code) by utilizing TypeScript interfaces and JSDoc annotations. Our goal is to potentially transition to ...

Executing `removeChild` within a timeout during page load does not yield the expected results

I have an HTML div that is designed to contain dynamically generated children. These children are meant to be removed from the list after a specific amount of time (e.g. 1000 ms). Although some people have experienced scope issues with timeout functions, ...

Using Python Webdriver to Execute JavaScript File and Passing Arguments to Functions

How can I execute a JavaScript function and pass arguments to it? value = driver.execute_script(open("path/file.js").read()) I have successfully executed the file, but I am unsure of how to pass arguments to the function within it. Any suggestions would ...

Angular Bootstrap uibModal is failing to resolve attributes

Issue with Roles in AngularJS Bootstrap uiModel var modalInstance = $uibModal.open({ animation: $scope.animationsEnabled, templateUrl: 'myModalContent.html', controller: 'ModalInstanceCtrl', size: 100, resolve: { roles: f ...

Retrieving JQuery Results Based on List Items

Once I have obtained the list id from the navigation, my next step is to send the id to a PHP file that will return a JSON list. Below is the jQuery syntax I am using: $("#ul_navigation li").click(function(e) { idsec = this.id; alert(idse ...

Freezing objects using Object.freeze and utilizing array notation within objects

Could someone kindly explain to me how this function operates? Does [taskTypes.wind.printer_3d] serve as a method for defining an object's property? Is ["windFarm"] considered an array containing just one item? Deciphering another person& ...