0

I have an array of timestamps and I want to transform it into dates.

timestamps = [1568666854141, 1568595225048, 1568594645595];
timestamps.forEach(function(d) { d = new Date(d) } )

When I do new Date(d) in debug it gives me Mon Sep 16 2019 16:47:34 GMT-0400 which is good, but if I check my array, it's still the same. It gives me [1568666854141, 1568595225048, 1568594645595] instead of [Mon Sep 16 2019 16:47:34 GMT-0400, ...] Why does not every element d reassigns to a date?

1
  • 1
    you're just reassigning the variable d, it has no affect on the original array, you should do it like so timestamps.forEach(function(d, i) { timestamps[i] = new Date(d) } ) Commented Nov 15, 2019 at 1:54

3 Answers 3

3

forEach can not modify the orgin array, please use map:

let timestamps = [1568666854141, 1568595225048, 1568594645595];
timestamps = timestamps.map(function(d) { return new Date(d) } )
Sign up to request clarification or add additional context in comments.

1 Comment

map doesn't modify the original array either. ;-) forEach can be used, though map is more semantic.
1

You're creating a new array and creating a new (correct) date value for each element, but not doing anything with the values.

timestamps = timestamps.map(function(d) { return new Date(d) } );

Comments

0

I solved my problem doing this:

timestamps.forEach(function(elem, idx, arr) {arr[idx] = new Date(elem); });

2 Comments

You should use map for this instead (see my answer as well as the other answer); especially if you don't need access to that array for all of the other values.
map and forEach otherwise behave very similarly; but this is an important case where you can really benefit from the fact that map returns an array for you. (Check out the link in my answer below for more details on this specifically.)

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.