Reputation: 371
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?
Upvotes: 0
Views: 1978
Reputation: 31
forEach can not modify the orgin array, please use map:
let timestamps = [1568666854141, 1568595225048, 1568594645595];
timestamps = timestamps.map(function(d) { return new Date(d) } )
Upvotes: 3
Reputation: 371
I solved my problem doing this:
timestamps.forEach(function(elem, idx, arr) {arr[idx] = new Date(elem); });
Upvotes: 0
Reputation: 2399
You're creating a new array and creating a new (correct) date value for each element, but not doing anything with the values.
timestamps
array) by using map
instead of forEach
[link to good explanation of the difference]timestamps = timestamps.map(function(d) { return new Date(d) } );
Upvotes: 1