Creating a collection of time elements

My current array consists of various time values, such as:

//     '6:00pm',
//     '7:00pm',
//     '8:00pm',
//     '9:00pm',
//     '10:00pm',
//     '11:00pm',
//     '12:00am',
//     '1:00am',
//     '2:00am',
//     '3:00am',
//     '4:00am',
//     '5:00am',
//     '6:00am',
//     '7:00am',
//     '8:00am',
//     '9:00am',
//     '10:00am',
//     '11:00am',
//     '12:00pm',
//     '1:00pm',
//     '2:00pm',
//     '3:00pm',
//     '4:00pm',
//     '5:00pm',

I am looking to format these times into objects like the example below:

[
    {
      time: "6:00",
      Meridiem: "pm"
   },
   {
      time: "7:00",
      Meridiem: "pm"
   }
]

However, I am facing a roadblock when trying to loop through the times and need assistance. My attempted solution so far includes:

const array = new Array(12);
let timeArray = [];
for(var i=1;i<=array.length;i++){
    let x = {
        time: i,
        meridium: "AM"
    }
    timeArray.push(x);
};

console.log(timeArray, 'timeArray')

I am aware that this is not correct. Could someone provide guidance on how to achieve the desired output?

Answer №1

If you're looking to dynamically create an array in your code, one approach is to utilize the Array constructor along with the fill method to populate it, and then map the indices to their corresponding time values. To compute the time, you can use the modulo operator (%) to handle cases where the index % 12 results in 0, which should be replaced with 12.

To generate a 24-hour array starting at 6 PM, you can first create a complete 24-hour array, split it at the 6 PM mark (index 18), and concatenate the two halves back together using methods like slice and spread syntax depending on your specific requirements.

let times = Array(24).fill().map((_, i) => ({
  time: `${i % 12 || 12}:00`,
  Meridiem: i < 12 ? "am" : "pm"
}));

times = [...times.slice(18), ...times.slice(0, 18)];

console.log(times);

Answer №2

For transforming each item in your array, consider using the Array.map method.

var arr = ['1:00pm',
    '2:00pm',
    '3:00pm',
    '4:00pm',
    '5:00pm',];
var newArr = arr.map(item =>{
  return {
    time: item.substring(0, item.length - 2),
    meridium : item.substring(item.length - 2),
  }
})

console.log(newArr)

Answer №3

If you want to format a time array, you can utilize the map function along with the slice method as shown in the code snippet below.

const listOfTime = ['6:00pm','7:00pm','8:00pm','9:00pm','10:00pm','11:00pm','12:00am','1:00am','2:00am','3:00am','4:00am','5:00am','6:00am','7:00am','8:00am','9:00am','10:00am','11:00am','12:00pm','1:00pm','2:00pm','3:00pm','4:00pm','5:00pm'];

var formattedTime = listOfTime.map(function(val,index) {
  return {hour: val.slice(-2,listOfTime[index].length), meridiem: val.slice(0,listOfTime[index].length-2)};
})

console.log(formattedTime);

Answer №4

To format time values, you can either use the slice method or substring

const ArrOfTimeValues = ['6:00pm','7:00pm','8:00pm','9:00pm'];

const FormattedArr = [];
const ArrLength = ArrOfTimeValues.length;
for(let i = 0;i<ArrLength;i++){
  let ItemLength = ArrOfTimeValues[i].length;
  let Meridiem = ArrOfTimeValues[i].slice(-2,ItemLength);
  let TimePoints = ArrOfTimeValues[i].slice(0,ItemLength-2);
  let NewItem = {
    time:TimePoints,
    Meridiem:Meridiem
  }
  FormattedArr.push(NewItem);
}
console.log(FormattedArr);

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

Can someone please help troubleshoot my ajax code?

My ajax function is calling a php page, but I keep encountering an issue where the error function is being triggered instead of the success function. What could be causing this unexpected behavior? Here is my ajax code: function register() { $.ajax({ ...

Is there a way to hold off passing props until after setState() has completed?

I wrote a function named renderLayers that iterates through each object in the filterState array and copies those with the checked property set to true. const [layers, setLayers] = useState([]); (...) const renderLayers = () => { const ne ...

Is it possible to bulk update a sorted set using the Redis client in Node.js?

Looking to update multiple records in a sorted set using Redis client in Node.js. Currently, I am able to update a single record with client.zAdd(key,{score:score, value:memberId}). Is there a command or function that allows for bulk updates in Redis? I se ...

Retrieving specific information from a JSON file using Angular

I am looking to sort students by their class and then display them in an HTML format. Check out the code snippet here: http://plnkr.co/edit/GG9EYmPlIyD4ZM0ehaq6?p=preview .html code: <div ng-controller="ClassController"> <table> ...

Encountering a Java OutOfMemory Heap Space error when attempting to create massive double arrays with over 60 million entries

My goal is to create arrays of type double that can grow to sizes exceeding 60 million. Additionally, I need to continuously generate larger arrays by starting with a size of, for example, 20,000 and increasing it iteratively through my code multiple times ...

You can update a JavaScript string by adding values using the '+=' operator

I have the following function: function generateJSONstringforuncheckedfilters(){ jsonstring = ''; jsonstring = "["; $('body').on('click', 'input', function(){ jsonstring += "[{'OrderGUID&apo ...

Ways to update or define a cookie's value using angularJS

The name of the cookie is "NG_TRANSLATE_LANG_KEY" I have a question: How can I modify the value of this cookie from "ru" to another value, such as "fr" or "kk" using AngularJS? ...

Establishing a universal function within Ionic AngularJS

I have the following code snippet, where I have added a reset function that I want to be able to use from ng-click in any part of any template. angular.module('starter', ['ionic', 'starter.controllers', 'starter.services ...

Node.js with PostgreSQL (pg): The client connection has already been established. Reusing the client is not allowed

Currently, I am working on creating a basic register/login system and I'm facing an issue with checking for existing usernames. Here are the steps I've followed: Visit the localhost:3000/users/register page Input all required details and click o ...

Ways to implement a table column as a slider

My goal is to create a single-page website with a table as the main content. The first column of this table should be toggleable by a button. I specifically want to display the first column of the table only on the slidebar and not both the table and the ...

Vuetify Autocomplete that allows for adding values not in the predefined list

I am utilizing a vuetify autocomplete component to showcase a list of names for users to select from. In the case where a user enters a name not on the list, I want to ensure that value is still accepted. Check out my code snippet below: <v-autocomplete ...

Can a PHP script be executed through an Ajax event?

Is it feasible to execute the script of a PHP file when an AJAX event is triggered? Consider this scenario: on the AJAX error, could we send the data to the error.php file, record the error, notify the admin via email, and perform any other desired action ...

Providing annotations for Google Closure Compiler to accept 'zero or more parameters of any type'

I have a function that is similar to jQuery.noop, angular.noop, and goog.nullFunction. It essentially does nothing and returns undefined, but it comes in handy when used like this: callback(successFn || noop);. This function is flexible and can be invoked ...

utilizing a modal to trigger a function within the parent scope of an Angular application

I have a main.controller.js where there is a modal in place to notify the user of a warning before proceeding to the rest of the application. For example, I want to trigger my fileNew function from the modal. In main.controller.js: $scope.warningMod ...

Introducing additional fields with variable field names will result in all field names being identical

I am trying to implement a feature where clicking on the add button adds a new field to the page within a hidden div. // Hidden div containing the field <div class="dependent-row" style="visibility: hidden;"> <div class="row" style="border:1p ...

Attempting to create a lineup of bricks with varying widths that are directly related to the overall width of the canvas

I'm attempting to create a row of randomly sized bricks on a canvas. The bricks should have varying lengths, but must stay within the confines of the canvas. The canvas has a length of 400, and I want there to be a 10px padding on each side between ...

The error message "Component prop is not valid when using redux-react in conjunction with react-router" is displayed

After implementing connect from react-redux in my project, the react router started to have trouble recognizing my react component as a valid component. This resulted in a warning stating: Failed propType: Invalid prop component supplied to Route index.js ...

Using an array of references in React

I've encountered a problem where I'm trying to create a ref array from one component and then pass it to another inner component. However, simply passing them as props to the inner component doesn't work as it returns null. I attempted to fo ...

Arranging data by last name when the first and last names are combined in a single field of the

My datatable is set up with basic fields and data rows, including a column for customer names that combine both first and last names. Is there a way to modify the sorting method in datatables to sort based on the surname (last word) within this column? ...

Issue with ReactJS on the server side rendering

Could someone please help me understand my current issue? On the server side (using Node.js), I have the following code: var React = require('react'); var ReactDOMServer = require('react-dom/server'); var TestComponent = React.create ...