2

I'm trying to convert my date string into an array.

Date string: var date = "2017,03,23";

Desired result: [2017,03,23]


Here is what I tried:

var new_date = date.split(','); // result: ["2017", "03", "23"]

I want [2017,03,23].

How do I do this?

4 Answers 4

4

this should do:

var date = "2017,03,23";
var array = date.split(",").map(Number);
console.log(array);

Sign up to request clarification or add additional context in comments.

Comments

1

You can parseInt the array!

var date = "2017,03,23";
date = date.split(',');
for(var i=0; i<date.length; i++) { date[i] = parseInt(date[i], 10); }
console.log(date);

2 Comments

I think date.split(',').map(Number) is somewhat shorter. ;-)
Little overloading in here for sure. ;)
1

You're getting an array of String, instead of an array of int. You just need to convert the array you have into ints in a new array. Here's an example, using parseInt():

var new_date = date.split(',');
for(i = 0; i < new_date.length; i++){
    new_date[i] = parseInt(new_date[i]);

Comments

1

Better and short way would be using

var date ="2017,03,23";
var output = date.split(',').map(Number);
console.log(output);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.