how to make the empty value for the day using moment - javascript

I want to plot the data for the week in bar chart, how to give the empty value if the date is not there in the response object. I am using moment and lodash groupby for the find which day for the week.
const actionHistory = [
{
"c_code": "FIELD_VISIT",
"amtp_actionTaken": "call",
"amtp_takenOn": "2023-01-13T18:28:12.850Z"
},
{
"c_code": "FIELD_VISIT",
"amtp_actionTaken": "call",
"amtp_takenOn": "2023-01-11T18:28:12.850Z"
}
];
const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const month = groupBy(actionHistory, (dt) => moment(dt?.amtp_takenOn).days());
const result = map(month, (el, i) => ({ value: el?.length, label: weekdays[i - 1], frontColor: '#177AD5' });`
if i put console.log to result I getting the only the aviable date week days like this
[{"value":1,"label":"Tue","frontColor":"#177AD5"},{"value":1,"label":"Thu","frontColor":"#177AD5"}]
my expected output should be.
[{"value":0,"label":"Sun","frontColor":"#177AD5"},
{"value":0,"label":"Mon","frontColor":"#177AD5"},
{"value":1,"label":"Tue","frontColor":"#177AD5"},
{"value":1,"label":"Wed","frontColor":"#177AD5"},
{"value":1,"label":"Thu","frontColor":"#177AD5"},
{"value":0,"label":"Fir","frontColor":"#177AD5"},
{"value":0,"label":"Sat","frontColor":"#177AD5"}]

This will do the trick
const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
let result = [{ "value": 1, "label": "Tue", "frontColor": "#177AD5" }, { "value": 1, "label": "Thu", "frontColor": "#177AD5" }];
result = weekdays.map((day, i) => {
const res = result.findIndex(({ label }) => label === day); // is label === day
if (res !== -1) return result.splice(res, 1)[0]; // return the object
return { "value": 0, "label": day, "frontColor": "#177AD5" }; // else return an object with value 0
})
console.log(result)

Maybe this is what you are looking for?
const actionHistory = [
{
"c_code": "FIELD_VISIT",
"amtp_actionTaken": "call",
"amtp_takenOn": "2023-01-13T18:28:12.850Z"
},
{
"c_code": "FIELD_VISIT",
"amtp_actionTaken": "call",
"amtp_takenOn": "2023-01-11T18:28:12.850Z"
}
];
const [start,end]=actionHistory.map(el=>new Date(el.amtp_takenOn).getDay()).sort();
const res="Sun,Mon,Tue,Wed,Thu,Fri,Sat".split(",").map((wd,i)=>
({value:+(i>=start&&i<=end),label:wd,frontColor:'#177AD5'}));
console.log(JSON.stringify(res));
There are quite a few assumptions in my snippet:
the datetime values in the objects of array actionHistory are being interpreted as start and end dates. I sort them from smaller to larger weekday values (0 to 6 for Sunday to Saturday), so the starting weekday will have a smaller value than the ending weekday.
"2023-01-13T18:28:12.850Z" is a Friday and "2023-01-11T18:28:12.850Z" is a Wednesday.
all dates within the span defined by start and end will be given the value 1 and all others the value 0.

Related

Get last five years values array in JavaScript

[{ label: "2022", value: "2022" }, {label: "2021", value: "2021"},{label: "2020", value: "2020"}, {label: "2019", value: "2019"}]
First, you need to get the current year with new Date().getFullYear().
Now, you need to generate an array and modify it:
Use the Array constructor with the arrayLength parameter, to generate an array with a specific length
Prefill the array with the current year using the fill() method
Using the map() method, subtract with the index to count the years downwards
Using the map method again, convert the year to string and finally to the object in the desired format
Result:
const currentYear = new Date().getFullYear();
const result = new Array(5)
.fill(currentYear)
.map((year, i) => year - i)
.map(year => year.toString())
.map(stringifiedYear => ({ value: stringifiedYear, label: stringifiedYear }));
console.log(result);

Get common data from multiple arrays of object that containing a unique id and nested array using javascript es6

I am trying to find the common data from multiple arrays of object that contains a unique id (mongoose object id) and an array of string.
for example:
array1 = [{
_id: "60f027f98b55eb2df1f36c04",
date: "2021-07-15T12:18:12.223Z",
time: "30",
hours: ["8:00 AM", "8:30 AM"]
}]
array2 = [{
_id: "60f027f98b55eb2df1f36c05",
date: "2021-07-15T12:18:12.223Z",
time: "60",
hours: ["7:30 AM", "8:30 AM", "9:30AM"]
}]
array3 = [{
_id: "60f027f98b55eb2df1f36c06",
date: "2021-07-16T12:12:12.223Z",
time: "30",
hours: ["7:00 AM", "8:30 AM"]
}]
The output should have maximum common values in the arrays for maximum common dates and that date should have maximum common hour.
So the sample output should look something like this.
common_data = {
date: "2021-07-15T12:18:12.223Z",
time: "30",
hours: "8:30AM"
}
I looked up at other answers and tried something like this:
merged all the arrays and
let result = merged_slots_array.shift().filter(function(v) {
return merged_slots_array.every(function(a) {
const matchDate = a.date === v.date;
const getMatchTime = a.hours.shift().filter(function(x) {
return v.hours.every(function(t) {
return x.indexOf(t) !== -1;
})
});
return matchDate && getMatchTime
});
});
but getting error merged_slots_array.shift(...).filter is not a function
After concatenating the arrays, finding the max common hour can be done through a filter that only keeps duplicates, then gets sorted. Once we have that, we can query each array to make sure it contains the max hour, then extract the max date and time. My output was slightly different than yours because i filtered for the max time, hour and date
array1 = [{
_id: "60f027f98b55eb2df1f36c04",
date: "2021-07-15T12:18:12.223Z",
time: "30",
hours: ["8:00 AM", "8:30 AM"]
}]
array2 = [{
_id: "60f027f98b55eb2df1f36c05",
date: "2021-07-15T12:18:12.223Z",
time: "60",
hours: ["7:30 AM", "8:30 AM", "9:30AM"]
}]
array3 = [{
_id: "60f027f98b55eb2df1f36c06",
date: "2021-07-16T12:12:12.223Z",
time: "30",
hours: ["7:00 AM", "8:30 AM"]
}]
const getCommon = (arrays) => {
let group = [].concat.apply([], [...arrays])
let hour = group.map(e=>e.hours).flat().filter((e,i,a) => a.indexOf(e) !== i).sort((a,b) => a.localeCompare(b))[0]
let common = group.filter(e=>e.hours.includes(hour))
let time = Math.max(...common.map(e => +e.time))
let date = common.map(e => e.date).sort((a,b) => new Date(b) - new Date(a))[0];
return {date: date, time: time, hours: [hour]}
}
let arg = []
arg.push(array1)
arg.push(array2)
arg.push(array3)
console.log(getCommon(arg))
TS Playground

How to get the sum of values per day grouped by day from an array in JS? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
In JS, given an array of objects, like:
[{
date: 1525655429184,
value: 20.00
},{
date: 1525655429184,
value: 3.99
},{
date: 1526001029184,
value: 19.00
},{
date: 1526001025184,
value: 4.30
}]
Where the 'date' property is a date in milliseconds, and the 'value' property is a monetary represented by a float, and each object of this array can be one day of the month with his associated value.
I want to get the sum of value for each week day, to show in a chart of total values x day.
So the output should be like this example:
[
{ day: 'Sun', sum: 23.99 },
{ day: 'Mon', sum: 0 },
{ day: 'Tue', sum: 22.2 },
{ day: 'Wed', sum: 22.3 },
{ day: 'Thu', sum: 2.2 },
{ day: 'Fri', sum: 32.2 },
{ day: 'Sat', sum: 22.43 },
]
First, you need to convert the date (which i believe in milliseconds) into date and get the day by using getDay(). Create an array of days, loop thru the days, and if the converted date is the same as the day sum the values. Take a look at the snippet below.
var data = [{
date: 1525655429184,
value: 20.00
}, {
date: 1525655429184,
value: 3.99
}, {
date: 1526001029184,
value: 19.00
}, {
date: 1526001025184,
value: 4.30
}]
var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var sumVals = [];
var daysSum = [];
var sumVal = days.forEach(function(day) {
var total = 0;
data.forEach(function(items) {
var d = new Date(items.date);
var formattedD = days[d.getDay()];
if (day === formattedD) {
total += parseFloat(items.value);
}
})
sumVals.push(total)
daysSum.push([day, total])
})
console.log(days)
console.log(sumVals)
console.log(daysSum)//just to show if it matches
Milliseconds in a day:
var millsperday = 1000*60*60*24;
Current millisecond/day offset:
var d = new Date();
var m = d.getTime();
d.setHours(0,0,0,0);
var o = d.getTime()-m;
So, to divide a list of (unixtime) milliseconds:
for (i=0;i<list.length;i++) {
numberofday = Math.floor((list[i]-o)/millsperday) ;
}

How to use Moment.JS to check whether a timestamp is between 2 other timestamps

I have the following JSON array (note these are only the 5th and 6th elements of the array):
[
{
Day: 'Mon',
EndTime: '{ts \'1970-01-01 18:00:00\'}',
StartTime: '{ts \'1970-01-01 16:30:00\'}',
courseName: 'Computer Science 250: Introduction to Website Design',
Credits: '4'
},
{
Day: 'Mon',
EndTime: '{ts \'1970-01-01 18:30:00\'}',
StartTime: '{ts \'1970-01-01 17:30:00\'}',
courseName: 'Math 220: Differential Equations',
Credits: '3'
}
]
The data in the array is sorted by the values of the 'EndTime'. When I try to check whether the end time of the object at i - 1 (18:00:00) is between the start time and end time of the next object (at i which if 17:30:00 to 18:30:00) I should get true, but instead the isBetween method returns false.
How can I fix this, I know I am making some kind of simple mistake?
Here is my code:
for(let i = 1; i < monday.length-1; i++) {
const year = '1970-01-01';
const format = 'DD/MM/YYYY hh:mm:ss a';
var next_endtime = monday[i].EndTime.substr(16, 8);
var next_starttime = monday[i].StartTime.substr(16, 8);
var prev_endtime = monday[i-1].EndTime.substr(16, 8);
var plesson_e = moment(year + 'T' + prev_endtime, format),
nlesson_start = moment(year + 'T' + next_starttime, format),
nlesson_end = moment(year + 'T' + next_endtime, format);
var testbool = moment(plesson_e).isBetween(nlesson_start, nlesson_end, 'time');
console.log(testbool);
}
The string you pass to moment does not match your specified format :
const year = '1970-01-01'; // => see the '-', and the year is first
const format = 'DD/MM/YYYY hh:mm:ss a'; // => you put '/' and day first
Try changing the format value to:
const format = 'YYYY-MM-DD hh:mm:ss a';
See this fiddle
There is something wrong with the datetime or format, which you pass to moment JS, it works for me:
const monday = [{
Day: 'Mon',
EndTime: '{ts \'1970-01-01 18:00:00\'}',
StartTime: '{ts \'1970-01-01 16:30:00\'}',
courseName: 'Computer Science 250: Introduction to Website Design',
Credits: '4'
},
{
Day: 'Mon',
EndTime: '{ts \'1970-01-01 18:30:00\'}',
StartTime: '{ts \'1970-01-01 17:30:00\'}',
courseName: 'Math 220: Differential Equations',
Credits: '3'
}
]
const format = 'hh:mm:ss a';
var next_endtime = monday[1].EndTime.substr(16, 8);
var next_starttime = monday[1].StartTime.substr(16, 8);
var prev_endtime = monday[0].EndTime.substr(16, 8);
var plesson_e = moment(prev_endtime, format),
nlesson_start = moment(next_starttime, format),
nlesson_end = moment(next_endtime, format);
var testbool = moment(plesson_e).isBetween(nlesson_start, nlesson_end, 'time');
console.log(next_endtime, next_starttime, prev_endtime);
console.log(nlesson_end, nlesson_start, plesson_e);
console.log(testbool);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>

Array inside a JavaScript Object?

I've tried looking to see if this is possible, but I can't find my answer.
I'm trying to get the following to work:
var defaults = {
'background-color': '#000',
color: '#fff',
weekdays: {['sun','mon','tue','wed','thu','fri','sat']}
};
It just gives an error, and I've tried using ({...}) and [{...}] I'd like to be able to access the weekdays using something like:
defaults.weekdays[0];
is this possible?
Kill the braces.
var defaults = {
backgroundcolor: '#000',
color: '#fff',
weekdays: ['sun','mon','tue','wed','thu','fri','sat']
};
// define
var foo = {
bar: ['foo', 'bar', 'baz']
};
// access
foo.bar[2]; // will give you 'baz'
var data = {
name: "Ankit",
age: 24,
workingDay: ["Mon", "Tue", "Wed", "Thu", "Fri"]
};
for (const key in data) {
if (data.hasOwnProperty(key)) {
const element = data[key];
console.log(key+": ", element);
}
}
If you are so organised you may declare the entire object from the outset (this comma-delimited list is called an object initializer):
const myObject = {
string: 'Galactic Rainbows',
color: 'HotPink',
sociopaths: [ "Hitler", "Stalin", "Gates" ]
}
Alternatively, once you have declared the object,
// this line is the declaration:
const myObject = {};
// it is equivalent to:
const myObject2 = new Object();
you may define its properties by giving them values:
myObject.string = "Galactic Rainbows";
myObject.color = "HotPink";
myObject.sociopaths = [ "Hitler", "Stalin", "Gates" ];
// ^properties ^values
All examples below assume the object is already declared (as above)
I prefer to declare the array separately, like this, and then assign it to the object:
const weekdays = [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ];
myObject.weekdays = weekdays;
myObject.weekdays[0]
// => 'sun'
But if you have already declared the object, it would be quicker to code:
myObject.weekdays = [ 'sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat' ];
But you cannot assign an array of arrays to the object like this:
myObject.girlsAndBoys[0] = [ "John", "Frank", "Tom" ]; //Uncaught TypeError: Cannot set property '1' of undefined
myObject.girtsAndBoys[1] = [ "Jill", "Sarah", "Sally" ]; //Uncaught TypeError: Cannot set property '1' of undefined
To assign a two dimensional array to an object you have a few options. You can initialise the empty 2D array first:
myObject.girlsAndBoys = [[]];
myObject.girlsAndBoys[0] = [ "John", "Frank", "Tom" ];
myObject.girtsAndBoys[1] = [ "Jill", "Sarah", "Sally" ];
Or you may do it layer by layer:
const boys = [ "John", "Frank", "Tom" ];
const girls = [ "Jill", "Sarah", "Sally" ];
myObject.girlsAndBoys = [[ boys ],[ girls ]];
Alternatively you may do it all at once (after no more than the object declaration):
const myObject = {};
myObject.girlsAndBoys = [[ "John", "Frank", "Tom" ],
[ "Jill", "Sarah", "Sally" ]];
myObject.girlsAndBoys[0][0] == "John"; // returns True
var defaults = {
"background-color": "#000",
color: "#fff",
weekdays: [
{0: 'sun'},
{1: 'mon'},
{2: 'tue'},
{3: 'wed'},
{4: 'thu'},
{5: 'fri'},
{6: 'sat'}
]
};
console.log(defaults.weekdays[3]);
var obj = {
webSiteName: 'StackOverFlow',
find: 'anything',
onDays: ['sun' // Object "obj" contains array "onDays"
,'mon',
'tue',
'wed',
'thu',
'fri',
'sat',
{name : "jack", age : 34},
// array "onDays"contains array object "manyNames"
{manyNames : ["Narayan", "Payal", "Suraj"]}, //
]
};
In regards to multiple arrays in an object. For instance, you want to record modules for different courses
var course = {
InfoTech:["Information Systems","Internet Programming","Software Eng"],
BusComm:["Commercial Law","Accounting","Financial Mng"],
Tourism:["Travel Destination","Travel Services","Customer Mng"]
};
console.log(course.Tourism[1]);
console.log(course.BusComm);
console.log(course.InfoTech);

Categories