Transform the array of strings

I'm currently working with an array that looks like this:

["[Date.UTC(2016,09,30),250500.00]","[Date.UTC(2016,09,29),255100.83]", "[Date.UTC(2016,09,28),255600.82]"]

What would be the best way to transform it into a structure like this?

[[Date.UTC(2016,09,27),256100.83],[Date.UTC(2016,09,25),261091.57],[Date.UTC(2016,09,23),261391.58]]

This task is part of my work in AngularJS.

Answer №1

Here it is.

It may not be the prettiest solution, but it definitely gets the job done without relying on eval.

var nums = ["[Date.UTC(2019,11,25),20000.50]","[Date.UTC(2019,11,26),30010.75]", "[Date.UTC(2019,11,27),35005.82]"];
var output = nums.map(function(item){
    var data = JSON.parse(item.replace('Date.UTC(', '').replace(')', '').replace(/,0/g, ','));
    return [new Date(data[0], data[1], data[2]), data[3]];
});
console.log(output);

This code snippet will give you an array with dates formatted as JS Date objects.

Answer №2

give this a shot

const data = [
  "[Date.UTC(2016,09,30),250500.00]",
  "[Date.UTC(2016,09,29),255100.83]", 
  "[Date.UTC(2016,09,28),255600.82]"
]

const newData = data.map(entry => {
  const cleanedEntry = entry
    .replace('[Date.UTC(', '')
    .replace(']', '')
    .replace(')', '')
  
  const splitEntry = cleanedEntry.split(',')
  
  const year = splitEntry[0]
  const month = splitEntry[1]
  const day = splitEntry[2]
  const updatedEntry = [
     Date.UTC(year, month, day),
     Number(splitEntry[3])
  ]
  
  return updatedEntry
})

console.log(newData)

Answer №3

Check out this clever solution utilizing regex! It's interesting to note that in JavaScript dates, months are zero-indexed.

console.log(["[Date.UTC(2016,09,30),250500.00]","[Date.UTC(2016,09,29),255100.83]", "[Date.UTC(2016,09,28),255600.82]"].map(function(i){
  var afloat;
  var date = /Date\.UTC\((\d{4}),(\d{2}),(\d{2})\)/.exec(i);
  date = new Date(Date.UTC(+date[1], +date[2] - 1, +date[3]));
  afloat = +i.split('),')[1].split(']')[0];
  return [date, afloat];
}))

Answer №4

const input = ["[Date.UTC(2016,09,30),250500.00]","[Date.UTC(2016,09,29),255100.83]", "[Date.UTC(2016,09,28),255600.82]"]

const parseData = data => {
    const parsedArray = data.map(item => {
        const utcDateReplaced = item.replace(/Date\.UTC\((.*)\)/, function() {
            const argsRaw = arguments[1];
            const args = argsRaw.split(',');
            return Date.UTC.apply(Date, args);
        });

        return JSON.parse(utcDateReplaced);
    });

    return parsedArray;
}

const result = parseData(input);
console.log(result); 
// ===> [[1477785600000, 250500], [1477699200000, 255100.83], [1477612800000, 255600.82]]

http://jsbin.com/kohexuh/1/edit?js,console

Answer №5

There exists a compromise between georg's evaluation answer and Cerbrus's replacement answer. It operates similarly to eval, but without actually utilizing the eval function: new Function

var from = ["[Date.UTC(2016,09,30),250500.00]","[Date.UTC(2016,09,29),255100.83]", "[Date.UTC(2016,09,28),255600.82]"];
var to = from.map( e => new Function( 'return'+e )() ) // To array
             .map( ([a,b]) => [new Date(a), b] ); // date to Date

console.log( to );

This method is not foolproof, but it is concise and avoids some of the drawbacks typically associated with using eval.

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

"Creating a Miniview Panel on a Fabric Canvas: A Step-by-Step Guide

Is there a way to add a mini view panel to my Fabric Canvas like shown in this image MiniView Panel? I want a panel in the corner of my canvas that displays the entire layout. Similar to the panel on this website . ...

Add design to the footer during a specific event using Javascript

Here is the CSS code I am working with: .footer { font-family: "lato", sans-serif; padding: 20px; line-height: 1.2; text-align: right; background: #eee; color: #0D47A1; font-size: 13px; height: 80px; position: fixed; right: 0px; botto ...

Finding numerous keywords in a given text (Javascript)

Here is the code snippet I'm working with: // Finding multiple keywords within a text // Scenario 1 var inputText = "Hello, My name is @Steve, I love @Bill, happy new year!"; var terms = ["steve"]; var result = inputText.toLowerCase().search([terms]) ...

"Exploring the possibilities of integrating the Twitter API with

Currently, I am attempting to access my most recent tweet from Twitter using https://github.com/jdub/node-twitter I am interested in setting a variable, modifying that variable within a function, and then utilizing it again outside of said function. Is th ...

Leveraging the $broadcast method within a $interval function in AngularJS

After extensively searching this site and using Google, I have been unable to find a solution. I have one module dedicated to services and another for the app itself. In the services module, I have the following code snippet: $interval(function(){ $ro ...

Encountering issues with reading undefined properties while working with react-chartjs-2 and chart js

Having trouble with react chartjs errors? Visit the link for more details https://i.stack.imgur.com/lI2EP.png The versions I'm using are ^3.5.0 for chart.js and ^4.0.1 for react-chartjs-2 Tried downgrading to version 2 but it didn't solve the ...

Looking for a way to connect a background image in Vue CLI?

When running the code below, I encounter an issue. The code runs properly but the images are not displaying and instead showing the URL as unknown. How can I fix this problem? The images definitely exist. <template> <div class="slider">< ...

The controller in my template is not being passed by the $routeProvider

I attempted to dynamically load a template in Angular using ngRoute... However, I encountered an issue with the following code: (app.js route configuration) app.config(function($routeProvider) { $routeProvider.when("/password", { templateUrl ...

Currently, I am in the process of creating a game, but I am having trouble with my click event not functioning as expected on a dynamically

I'm currently working on a platform game and I've implemented a window.onload event that is supposed to trigger. Within this event, I am creating a div element, assigning it an ID, and then setting its onclick property. Despite being confident i ...

React function causing website to freeze upon dispatch

I created a function in the child component to handle checkbox selection and trigger setDispatch(true). Unfortunately, whenever I check the checkbox, the website freezes and stops responding until I close and reopen it. Here is the function: const [ ...

Can you explain the significance of this regular expression?

I'm trying to decipher the meaning of this regular expression. Can anyone help? "^[A-Z]{3}-[4-7]\d{2,4}\$$" My understanding is that it must start with exactly 3 uppercase letters and end with a sequence of 2, 3, or 4 digits (although I a ...

Display a div beside it when hovering over a specific part of the image

If I have an image that is 200px wide and 900px tall How can I make a div display alongside it when hovering over a specific section of the image? ...

Three.js globe experiencing issues with splines arc functionality

I have been experimenting with mapping arcs around a three.js globe, following some examples. I am close to getting it to work but I am struggling with the calculations and the resulting projection appears to be incorrect. If anyone could review my code an ...

The process of saving report filters and making them accessible for both running and scheduling tasks

I am facing a use case where I need to add query parameters to API calls and save them for future use. Essentially, I have a report that requires multiple filters to be saved - some predefined and others customizable. These saved filters can then be execut ...

Add an array to an existing array of objects

I am working with an array of objects displayed below. var myArray = [ { Data: '455', Note: 'tre', Id: '4' }, { Data: '456', Note: 'bre', Id: '5' }, { Data: '457', Note: 'cre&ap ...

Using jQuery to display the values of various keys in a nested array

Within my json data, there exists a nested array structured as such: var json.result= [ {"id":"0","category":"Camera","name":"600D Kit", "condition":"OK"}, {"id":"1","category":"Camera","name":"600D Kit", "condition":"missing cap"}, {"id":"2", ...

Unable to display Three.JS OBJ Model

I am facing an issue with loading a .obj model in Three.js. I created the model in Cinema 4D, exported it with a scale of 1 meter, and tried to load it using OBJLoader in Three.js. However, even though there are no errors, the model is not showing up. Wh ...

The "tsc" command in Typescript seems to be acting up. I've exhausted all possible solutions but

Hello there, I find myself struggling to run Typescript throughout the day while utilizing Visual Studio Code. My usual method involves installing TS globally: $ npm install -g typescript But every time I try to use it, I encounter the same error: bas ...

Calling Ajax inside each iteration loop

I have encountered numerous posts discussing this topic, but the solutions I came across do not quite suit my needs. Some experts suggest changing the code structure, however, I am unsure of how to go about doing that. What I desire: 1) Retrieve a list ...

Possible revised text: "Exploring methods for verifying elements within a div using Selenium

I have a situation where I need to verify elements within a div by using the following xpaths. The xpath for each item is as follows: Item 1:- //*[@id='huc-last-upsell-rows']/div[1]/div[2]/div[1]/div/div/a/img Item 2:- //*[@id='huc-last-u ...