Creating a structured representation of the week with 7 days

Recently, I've been utilizing the momentJS library to generate an array of 7 days in a week like this:

const moment = require('moment')
var startOfWeek = moment().startOf('week');
var endOfWeek = moment().endOf('week');

var days = [];
var day = startOfWeek;

while (day <= endOfWeek) {
    days.push(day.format("MMMM ddd DD, YYYY"));
    day = day.clone().add(1, 'd');
}

console.log(days);

The output gives me an array with the format of 7 days a week as shown below:

["December Sun 25, 2022","December Mon 26, 2022", "December Tue 27, 2022" , "December Wed 28, 2022", "December Thu 29, 2022", "December Fri 30, 2022", "December Sat 31, 2022"]

However, I am aiming for a different result structured like this:

const weekday = [
  {
    day: Mon,
    date: 26 
  },
  {
    day: Tue,
    date: 27 
  },
  {
    day: Wed,
    date: 28 
  },
  {
    day: Thu,
    date: 29 
  },
  {
    day: Fri,
    date: 30 
  },
  {
    day: Sat,
    date: 31 
  },
]

I am currently facing challenges in converting the data. Could someone assist me with this? Thank you!

Answer №1

To achieve the same outcome without relying on momentjs, native JavaScript Date methods such as toLocaleDateString can be utilized:

const day = new Date();  // Current date
day.setDate(day.getDate() - day.getDay() - 1);  // Most recent Saturday (excluding today)
const weekDays = Array.from({length: 7}, () => (
    day.setDate(day.getDate() + 1), {
        dayName: day.toLocaleDateString("en-US", { weekday: "short" }),
        date: day.getDate(),
    }
));

console.log(weekDays);

Answer №2

If you want to preserve the initial output for future use without altering the original code, one option is to iterate over the days array and create a new array based on the formatted string (ensuring conversion to an integer when needed).

const days = ["December Sun 25, 2022 ", "December Mon 26, 2022 ", "December Tue 27, 2022 ", "December Wed 28, 2022 ", "December Thu 29, 2022 ", "December Fri 30, 2022 ", "December Sat 31, 2022 "]

const weekday = days.map((formattedDate) => {
  const [_, day, dateString] = formattedDate.split(" ");
  return {
    day,
    date: parseInt(dateString)
  };
});

console.log(weekday);

Alternatively, you have the option to adjust your original code

//const moment = require('moment')
const startOfWeek = moment().startOf('week');
const endOfWeek = moment().endOf('week');

// uncomment if you still want `days`
// const days = [];
const weekday = [];
let day = startOfWeek;

while (day <= endOfWeek) {
    // days.push(day.format("MMMM ddd DD, YYYY "));
    weekday.push({ day: day.format("ddd"), date: day.date() });
    day = day.clone().add(1, 'd');
}

console.log(weekday);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

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

Angular Tips: Mastering the Art of Setting Multiple Conditions using ngClass

Currently, I am in the process of developing my own UI library by utilizing angular and Tailwind. However, I have encountered a challenge while using ngClass : <button [ngClass]="{ 'px-4 py-2 text-sm': size === 'md', ...

Mastering the BFCache management in React for optimal performance

Before redirecting to an external payment provider, I display a loading screen to account for longer load times. If the user decides not to complete the payment and navigates back using gestures or the browser's back button, the page is pulled from t ...

Using jQuery each with an asynchronous ajax call may lead to the code executing before the ajax call is completed

In my jQuery script, I utilize an each loop to iterate through values entered in a repeated form field on a Symfony 3 CRM platform. The script includes a $.post function that sends the inputted value to a function responsible for checking database duplicat ...

Dealing with MySQL reconnections in a Node.js REST application

Looking for assistance with my Node.js REST API connected to MySQL. I have encountered issues with the connection closing or timing out. Can someone help me troubleshoot my code: Server.js var express = require("express"); var mysql = require("mysql"); ...

Is there a way to seamlessly update a field without refreshing the page or overloading the server?

I'm intrigued by the concept of updating a field dynamically without refreshing the page or overwhelming the server with queries. Stackoverflow demonstrates this feature when someone answers our question, and it instantly shows at the top of the page. ...

Vue: restrict entry to the view unless props are configured

Currently, I am in the process of creating a Vue game that consists of two main views: a 'setup' view and a 'play' view. The values that are configured in the setup view are then passed as props to the play view, initiating the game wit ...

Obtaining the value of an item in an unordered list

Hi everyone, I have been trying to extract the value of <li> elements that display images horizontally. Below is the HTML code I am working with: <div id="layoutInnerOptions"> <ul id="navigationItemsContainer" class="layouts_list"> <l ...

NodeJS refuses to import a file that is not compatible with its structure

My website has two important files: firebase.js gridsome-server.js The firebase.js file contains JavaScript code related to Firebase integration: import firebase from 'firebase/app' import 'firebase/firestore' const config = { ap ...

Trouble with applying colors to mesh in Three.js

I have a mesh that I create and color according to user specifications using an HTML5 color picker. To retrieve the color value from the color picker, I use the following code: var colorChosen = $("#colorAgent").val() // it returns the value as: "#ff0080" ...

Navigate through different dates with a scrolling carousel

After developing a carousel for users to flick and scroll through dates using the slick library, I've encountered some minor issues as well as a major one. Take a look at the carousel on this link: Username: test Password: test I'll outline t ...

What's the most effective method for isolating elements in HTML to prevent one element from impacting another?

I recently created a password form in HTML with some nice functions. However, after making a small adjustment, the CSS is causing the elements to shift when clicking on different input boxes. This results in the labels on the form moving slightly up and do ...

Having trouble aligning a div in the middle of a slick-slider item using flex styling

I've created a slick slider component in Vue, and I'm facing an issue with centering a circular div inside each of the slider items. Despite trying to align and justify center along with adding margin:auto for horizontal centering, I can't s ...

Constructing a table using an array in React

I need assistance with creating a table based on salary data for different sectors. I have an array with example data that includes currencies and sectors. const data=[ ['Euro','Tech'], ['USD','Tech'], ['GBX&apo ...

What is the process for retrieving a list of image URLs from Firebase storage and then transferring them to Cloud Firestore?

Currently, I am working on uploading multiple images to Firebase Cloud Storage simultaneously. The process involves uploading the images, obtaining their URLs upon completion, adding these URLs to a list variable called urlsList, and then uploading this li ...

Class with an undefined function call

Currently, I am working with angular2 and TypeScript where I have defined a class. export class Example{ //.../ const self: all = this; functionToCall(){ //.. Do somerthing } mainFunctionCall(){ somepromise.then(x => self.fu ...

What is the reason behind Selenium not utilizing JavaScript?

I've been a beginner in the world of Javascript for a while now, with my main goal being to use it for creating Selenium automations as part of my journey into QA automation. However, I find myself quite perplexed when it comes to the language. In al ...

Creating directional light shadows in Three.JS: A Step-by-Step Guide

Can shadows be generated using a DirectionalLight? When I utilize SpotLight, shadows are visible. However, when I switch to DirectionalLight, the shadow functionality doesn't seem to work. ...

transferring information between different views in express.js

I am completely new to the world of express and node, so please be patient with me :D In my index.ejs file, I have a string that I need to pass to my viewActivity.ejs file. This string will be utilized in the JavaScript section of my viewActivity.ejs file ...

Enhance your JavaScript skills by deserializing objects and seamlessly integrating new methods

Currently in my Javascript code, I am utilizing localStorage. Since objects cannot be directly stored in it, I am using JSON.stringify to serialize them before saving. Within localStorage, I am storing the entire game state, where some of the sub-objects ...

Stop HTML audio playback upon clicking on a specific element

I'm looking to add background music to my website with a twist - a music video that pops up when the play button is clicked. But, I need help figuring out how to pause the background music once the user hits play. Play Button HTML - The play button t ...