Changing the structure of elements in an array using JavaScript

I am seeking a way to convert an array of strings, which represent dates in the format of 201001 ,201002, into something more readable like 2010 January, 2010 February. Do you have any suggestions on how to achieve this?

var Array = ["201005", "201006", "201007", "201008", "201009", "201010", "201011", "201012", "201101", "201102", "201103", "201104", "201106", "201107", "201108", "201109", "201110", "201111", "201112", "201201", "201202", "201203", "201204", "201205", "201206", "201207", "201208", "201209", "201210", "201211", "201212", "201301", "201302", "201303", "201304", "201305", "201306", "201307"];

The desired output would be :

var expected = ["2010 january", "2010 February" etc]

Answer №1

Here is a possible solution:

const monthList = {
  "01": "January",
  "02": "February",
  "03": "March",
  "04": "April",
  "05": "May",
  "06": "June",
  "07": "July",
  "08": "August",
  "09": "September",
  "10": "October",
  "11": "November",
  "12": "December"
};

xAxisValues = xAxisValues.map(value => {
  const year = value.substring(0, 4);
  const month = value.substring(4, 6);

  return `${year} ${monthList[month]}`;
});

An alternative approach would be to employ moment.js, although it might be too much for this task.

Answer №2

Feel free to test out my implementation

function formatDateTime(date) {
  var monthNames = [
    "January", "February", "March",
    "April", "May", "June", "July",
    "August", "September", "October",
    "November", "December"
  ];

  var monthIndex = date.getMonth();
  var year = date.getFullYear();

  return year + ' ' + monthNames[monthIndex];
}


var result = xAxisArray.map(item => {
  var strDate = item.slice(0, 4) + '-' + item.slice(4, 6) + '-01'

  return formatDateTime(new Date(strDate))
})
console.log(result)

Check out this demo: https://codepen.io/phuongnm153/pen/xxKgKYp

Answer №3

If you're looking to manipulate dates in JavaScript, you can utilize the following code snippet:

var dateArray = ["202005", "202006", "202007", "202008", "202009", "202010", "202011", "202012", "202101", "202102", "202103", "202104", "202106", "202107", "202108", "202109", "202110", "202111", "202112", "202201", "202202", "202203", "202204", "202205", "202206", "202207", "202208", "202209", "202210", "202211", "202212", "202301", "202302", "202303", "202304", "202305", "202306", "202307"];

//Mapping month numbers to names
const monthLabels = ["January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

//New array for formatted data
var formattedDates = [];

//Iterate through original array and format the date strings
dateArray.forEach(function(element) {
  var formattedDate = element.substr(0,4) + '-' + element.substr(4); //Insert dash between year and month
  var newDate = new Date(formattedDate); //Create new date object
  var year = newDate.getFullYear(); //Extract year
  var month = newDate.getMonth(); //Retrieve month

  formattedDates.push(year + ' ' + monthLabels[month]);
});

console.log(formattedDates);

To achieve this, convert string to date format, change it to the desired structure, and append the updated string to a fresh array.

Answer №4

If you wish to display the complete name of the month instead of just the first three letters, you must store all twelve months somewhere in your code, like this:

const MONTHS = [
  "January", "February", "March", "April", "May", "June",
  "July", "August", "September", "October", "November", "December"
];

After that, you can use the following function:

const format = (value) => {
  // assuming the format is 4 digits followed by 2 digits
  const [, year, month] = value.match(/(\d{4})(\d{2})/);
  return `${year} ${MONTHS[month - 1]}`
}

Finally, you can apply this function to your array like so:

const results = dataArray.map(format);

I hope this solution proves helpful!

Answer №5

One way to find your solution is by following this method.

xAxisArray.forEach(function(value , index){
    var last2 = value.slice(-2);
    const date = new Date(value.slice(4), last2);  // Example: 2009-11-10
    const month = date.toLocaleString('default', { month: 'long' });
    xAxisArray[index] = value.substring(0,4) +" "+ month;
});

This approach should help resolve your issue.

Answer №6

If you need to achieve this task, consider utilizing the moment library:

const newData = xAxisArray.map(entry => {
  const year = entry.substring(0,4)
  const month = entry.substring(4,2)
  return moment(`01/${month}/${year}`).format('YYYY MMMM')
})
console.log(newData)

Answer №7

Transform your data easily with moment.js library. Simply use the following expression:

moment("your value").format("YYYY MMM");

For example: moment(201005).format("YYYY MMM");

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

Receiving an error of "undefined" when trying to capture the selected

One issue I am facing is capturing the selected user option and sending that value in a post request. Let's put aside the post part since it's not directly related to the main question at hand. Currently, the value is showing up as undefined. ...

Encountering an Unexpected Token Error while using Jest in Next.js for node-modules

After setting up my Next.js project, I decided to install jest by running the command below: npm i --save-dev jest @testing-library/react @testing-library/jest-dom jest-environment-jsdom I then created a jest.config.json file with the following code snipp ...

Implementing a messaging feature with inbox functionality in a Node.js web application

In my node.js application, I am looking to incorporate a send message and inbox feature. The website focuses on job postings within a forum, catering to freelancers, mentors, and clients. To facilitate communication between these three types of users, I ...

Transferring data and parameters between the Client-Side and Server-Side

I am currently working on setting up an express.js server, but I am struggling to figure out how to send and receive data effectively. Specifically, I have an input field where users can enter their email addresses. I want this email address to be sent to ...

Having trouble escaping single quotes in JSON.stringify when using a replacer function

I'm attempting to replace single quotation marks in the values of my JSON string with \' however, it seems to not be working when I try to use the replacer function. var myObj = { test: "'p'" } var re ...

How to access data from a child component in a Vue 3 template

Within my project, there are three Vue components that utilize the Composite API with the setup option. My goal is to access data within a nested tree structure. The code below provides a simplified version of what I am trying to achieve. The application ...

Vue select is causing the selected choice of another selector to be influenced

Currently, I am facing an issue with a table displaying a specific Nova resource. The problem lies in the selectors within each row of the table - when one selector is changed, all other selectors automatically mirror that change. This behavior seems to be ...

Having trouble getting nodeJS socket.io to function properly on my Raspberry Pi

Being new to nodeJS and programming, I've been trying to get this piece of code to function properly with no success. It's frustrating because I can't figure out why it's not working, and I am clueless on how to troubleshoot it. Despite ...

Prevent the query from being executed by halting the AJAX call

Within my web application, I have a specific button that triggers an AJAX call upon being clicked. On the server side, I need to run a query against a database. I am concerned about the execution time of these queries and worry that users may be impatient ...

Is it possible to find out which JavaScript file the AJAX function is using to send a request to a Java servlet?

I am facing an issue with two js files, one.js and two.js. Both of these files make ajax requests to the same Java servlet class(AppController.java). Here is the code from one.js: function addOne(){ var formData = $('#form1').serialize(); ...

Merging a variable and its corresponding value in JavaScript

I am attempting to achieve a similar functionality in Angular javascript (with simplified code): var modelName = "date"; if (attrs.hasOwnProperty('today')) { scope.modelName = new Date(); } In the scenario above, my intention is for scope.m ...

Learn how to dynamically add a class to an element when hovering, and ensure that the class remains even after the mouse has

I'm facing difficulty with this task - when hovering over elements, an active class should be added to them. However, when moving the mouse to another section, the active class should remain on the last element hovered. Additionally, the first block s ...

Deliver JSX components that match one or more keys in the array of strings

Seeking assistance and guidance here. It seems like I might be overlooking something obvious. I am attempting to create a component that accepts either a string or string Array string[] as a property. const ComponentThatReturnsElement = (someElementName) = ...

Issues with AngularJS ng-view not functioning as expected

I recently followed a tutorial on AngularJS routing and views from this guide: However, I am facing an issue where changing the view does not trigger any response. Can anyone help me figure out what I might be doing wrong? Below is the code snippet that ...

Including extra js files disrupts the jQuery IntelliSense functionality

After enjoying the benefits of jQuery IntelliSense in VS2008, I decided to add a reference to jQuery UI. However, upon doing so, I noticed that the jQuery IntelliSense disappeared. It seems that referencing another .js file in the document causes this is ...

What is the reason behind ValidatorValidate() validating all RequiredFieldValidator controls on the page?

Can you explain why the function ValidatorValidate(v) validates all the RequiredFieldValidator controls on the page instead of just executing for RequiredFieldValidator1? Here is the code snippet: <html xmlns="http://www.w3.org/1999/xhtml"> ...

Tips for moving a div with a button in jQuery

I am working on a parent div that has an overflow set to hidden and it contains dynamically created children. I want to be able to scroll the parent div using two buttons - one for scrolling up and the other for scrolling down, as if the div had overflow-y ...

Displaying data metrics with Radar Charts in chart.js to illustrate point values

Is there a way to display the values on the chart using chart.js? UPDATE: I've tried using the options provided below but haven't been able to find a solution. options: { scale: { angleLines: { lineWidth: 0.5, colo ...

The designated origin in JavaScript is not displaying in the Django template

Sorry for the possibly silly question, but as I delve into Javascript and Django, I'm struggling with a specific issue. Despite spending hours on it, I can't seem to figure out why my image isn't displaying in my Django HTML template. Here ...

How come my function is executing right away despite the setTimeout() being called?

I am working on a program that is designed to showcase how a bubble sort works. However, I would like the program to pause for one second after each swap in order to clearly demonstrate the sorting process. Below is the code I have written: function bubble ...