In C#, I would use the following Dictionary
Dictionary << Date, int []>>
for having an array bound to a particular date. What would be the simplest way in JS to achieve the same?
I need to be able to alter the values in the integer array.
In C#, I would use the following Dictionary
Dictionary << Date, int []>>
for having an array bound to a particular date. What would be the simplest way in JS to achieve the same?
I need to be able to alter the values in the integer array.
Use the timestamp of that date as a key for a js object.
For example, let's say you want to map date a to array b:
const a = new Date();
const b = [1, 2, 3];
const c = {
[a.getTime()]: b,
};
in this case, c would be an object or hash map from date to array.
You can achieve an equal behaviour in Js in various ways.
Dicitionary could be replaced by a Map, or just an object ({}) with dynamic keys, however if you use an object you can only use strings as keys, anything else will be converted to a string. There is also a Date object in JS, however two dates representing the same date in time do not match:
const a = new Date(0), b = new Date(0);
console.log(a === b); // false
therefore they would not get stored in the same entry in the Map. Instead you could just stringify the Date, as strings are conpared by value. the int[] would just be an array of numbers in js.
const date1 = new Date(0);
const date1b = new Date(0);
const obj = {};
const map = new Map;
obj[date1] = [1, 2, 3];
// equals:
obj[date1.toString()] = [1, 2, 3];
map.set(date1, [1, 2, 3]);
map.set(date1.toString(), [3, 4, 5]);
console.log(
obj[date1b], // [1, 2, 3]
map.get(date1b), // undefined
map.get(date1b.toString()), // [3, 4, 5]
);
I only need to group by days
In that case, you'd have to generate a number or string out of the Date that only contains the day:
(new Date()).toString().split("T")[0] // 2018-12-11
Then use that string as the Maps / objects key.
Since you mentioned you are using momentjs, you could use the moment unix or toDate().getTime() to to get the date in ms and then utilize either an object or Map to get what you need:
let date1 = moment().unix()
let date2 = moment().add(7, 'days').unix()
let dict = {} // using object
dict[date1] = [1,2,3]
dict[date2] = [4,5,6]
console.log('dict via Object', dict[date1], dict[date2])
let dict2 = new Map() // using Map
dict2.set(date1, [1,2,3])
dict2.set(date2, [4,5,6])
console.log('dict via Map', dict2.get(date1), dict2.get(date2))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>