How do I find the latest time for each date in a JSON array? - javascript

I have this array in JSON format:
var result=[
{
"index": 13,
"id": 1122,
*

The approach below:
get a unique list of only the dates from the array i.e. dd/mm/yyyy
for each date in the unique list, create a sorted array per the times for that date
return the 0th item from that sorted array for that date
Example code:
var result = [
{
"index": 13,
"id": 1122,
"price": 100,
"dateTime": "11/12/2020 1:59"
},
{
"index": 14,
"id": 1122,
"price": 300,
"dateTime": "11/12/2020 3:15"
},
{
"index": 15,
"id": 1122,
"price": 314,
"dateTime": "11/13/2020 2:20"
},
{
"index": 16,
"id": 1122,
"price": 280,
"dateTime": "11/13/2020 2:23"
}
];
// get a list of the dates in result
// nothing fancy - the date is just a key
var dates = result.map(k => k.dateTime.substr(0, 10));
// get unique dates from this array
var uniqueDates = Array.from(new Set(dates));
// for each unique date, sort the times descending
// return the first item (latest) for that date
var filtered = uniqueDates.map(ud => {
var dateItems = result.filter(d => d.dateTime.substr(0, 10) == ud);
dateItems.sort((a, b) => (new Date(b.dateTime)).getTime() - (new Date(a.dateTime)).getTime());
return dateItems[0];
});
// output
console.log(filtered);

Sorting the Array on the Date value of dateTime, write a result array with dates-only as keys, retrieve the values of the result.
The TypeError, by the way, is because you should check for i + 1 being smaller than result.length in the loop (this will be falsy for the last element within the loop. In that case new Date(result[i+1].dateTime) will throw the error).
// initialize log helper
const log = Logger();
// create an empty Object
const result = {};
// sort data ascending
const dataSorted = getData().sort((a, b) =>
new Date(a.dateTime) - new Date(b.dateTime));
// add to result with datestring as key.
// The value with the most recent date will be preserved
// because key values are unique (so equal keys are overwritten)
dataSorted.forEach(v => result[new Date(v.dateTime).toDateString()] = v);
// the values of [result] contain the most recent records per date
log(Object.values(result));
// this can also be a one liner, using a reducer method
const resultX = Object.values(
getData()
.sort( (a, b) => new Date(a.dateTime) - new Date(b.dateTime) )
.reduce( (acc, value) =>
({...acc, [new Date(value.dateTime).toDateString()]: value}), {} )
);
log(`\n**from reducer`, resultX);
function getData() {
return [{
"index": 13,
"id": 1122,
"price": 100,
"dateTime": "11/12/2020 1:59"
},
{
"index": 14,
"id": 1122,
"price": 300,
"dateTime": "11/12/2020 3:15"
},
{
"index": 15,
"id": 1122,
"price": 314,
"dateTime": "11/13/2020 2:20"
},
{
"index": 16,
"id": 1122,
"price": 280,
"dateTime": "11/13/2020 2:23"
}
];
}
function Logger() {
const report = document.querySelector("#report") ||
document.body.insertAdjacentElement(
"beforeend",
Object.assign(document.createElement("pre"), {id: "report"}));
return (...args) => args.forEach(stuff =>
report.textContent += (stuff instanceof Object
? JSON.stringify(stuff, null, 2) : stuff) + "\n");
}

You can group the data based on date like,
const groups = data.reduce((groups, currVal) => {
const date = currVal.dateTime.split(' ')[0];
if (!groups[date]) {
groups[date] = [];
}
groups[date].push(currVal);
return groups;
}, {});
-> Here we split the date and and time part using split(' ') and took the date alone separately and form a group,
const date = currVal.dateTime.split(' ')[0];
And then you can get the recent date and time using the method,
groups[item].reduce((a, b) => (a.dateTime > b.dateTime ? a : b));
Working snippet:
const data = [
{
"index": 13,
"id": 1122,
"price": 100,
"dateTime": "11/12/2020 1:59"
},
{
"index": 14,
"id": 1122,
"price": 300,
"dateTime": "11/12/2020 3:15"
},
{
"index": 15,
"id": 1122,
"price": 314,
"dateTime": "11/13/2020 2:20"
},
{
"index": 16,
"id": 1122,
"price": 280,
"dateTime": "11/13/2020 2:23"
}
];
//Group the data based on date
const groups = data.reduce((groups, currVal) => {
const date = currVal.dateTime.split(' ')[0];
if (!groups[date]) {
groups[date] = [];
}
groups[date].push(currVal);
return groups;
}, {});
//Get the recent date and time based on each group
const result = [];
Object.keys(groups).filter(item => {
const newData = groups[item].reduce((a, b) => (a.dateTime > b.dateTime ? a : b));
result.push(newData);
});
console.log(result)

Related

sorting array and keeping only the last value of each day reactjs

i'm having a bit of a problem here, i have an array that looks like this :
const input = {
name: 'xy',
lastname: 'yx',
history: [
{ "value": 0.02, "date": "2022-08-02T23:03:22.895Z" },
{ "value": 0.04, "date": "2022-08-02T22:03:16.603Z" },
{ "value": 0.08, "date": "2022-08-02T21:03:20.378Z" },
{ "value": 0.02, "date": "2022-08-01T23:03:32.584Z" },
{ "value": 0.04, "date": "2022-08-01T22:03:30.311Z" }]
}
but it have more data and more dates than this exemple, i want to sort it into a new array and put only the newest value of each day
so it will look like this :
const input = {
name: 'xy',
lastname: 'yx',
history: [
{ "value": 0.02, "date": "2022-08-02T23:03:22.895Z" },
{ "value": 0.04, "date": "2022-08-02T22:03:16.603Z" },
{ "value": 0.08, "date": "2022-08-02T21:03:20.378Z" },
{ "value": 0.02, "date": "2022-08-01T23:03:32.584Z" },
{ "value": 0.04, "date": "2022-08-01T22:03:30.311Z" }],
newHistory:
{ "value": 0.02, "date": "2022-08-02T23:03:22.895Z" },
{ "value": 0.02, "date": "2022-08-01T23:03:32.584Z" }],
}
i currently did the sorting of all the dates but i'm having trouble in doing the rest.
Since you've already sorted your data you could use a single reduce to iterate over your array of sorted data while keeping track of a new output array.
For each data point, you compare its date by the last element of the output. If the year-month-day part is not the same, you add the data point to the output array.
Here are these steps written out in code:
const input = [
{ "value": 0.02, "date": "2022-08-02T23:03:22.895Z" },
{ "value": 0.04, "date": "2022-08-02T22:03:16.603Z" },
{ "value": 0.08, "date": "2022-08-02T21:03:20.378Z" },
{ "value": 0.02, "date": "2022-08-01T23:03:32.584Z" },
{ "value": 0.04, "date": "2022-08-01T22:03:30.311Z" } ];
const output = input.reduce(
(out, current) => {
const lastDate = out.at(-1)?.date.slice(0, 10);
const currentDate = current.date.slice(0, 10);
if (lastDate !== currentDate) {
out.push(current);
}
return out;
},
[]
);
console.log(output);
If you like one-liners, you could also write this as:
const input = [
{ "value": 0.02, "date": "2022-08-02T23:03:22.895Z" },
{ "value": 0.04, "date": "2022-08-02T22:03:16.603Z" },
{ "value": 0.08, "date": "2022-08-02T21:03:20.378Z" },
{ "value": 0.02, "date": "2022-08-01T23:03:32.584Z" },
{ "value": 0.04, "date": "2022-08-01T22:03:30.311Z" } ];
const output = input.reduce(
(out, current) => out.at(-1)?.date.slice(0, 10) === current.date.slice(0, 10) ? out : out.concat(current),
[]
);
console.log(output);
I think this is definitely a problem where splitting different tasks into functions helps make the code easier to understand.
You said in a comment that you wanted to group the calendar dates according to UTC time, but (if you change your mind) the code below will also allow you to optionally use the system time zone (as well as some other options).
I've included lots of comments to explain as you read, but feel free to ask for clarity in a comment if something still isn't clear.
'use strict';
/** #returns a stringified number with a minimum length */
function padN (n, maxLength = 2, fillString = '0') {
return String(n).padStart(maxLength, fillString);
}
/**
* #returns a default sorting algorithm function
* for an array of objects each having a specific key
*/
function createDefaultSortByObjKey (key, {reverse = false} = {}) {
return reverse
? (oA, oB) => oA[key] > oB[key] ? -1 : oA[key] < oB[key] ? 1 : 0
: (oA, oB) => oA[key] < oB[key] ? -1 : oA[key] > oB[key] ? 1 : 0;
}
/**
* Set the `utc` option to `true` to use UTC
* #returns a date string format like `"20220703"`
*/
function getSerializedYMD (date, {utc = false} = {}) {
const year = utc ? date.getUTCFullYear() : date.getFullYear();
const month = utc ? date.getUTCMonth() : date.getMonth();
const dayOfMonth = utc ? date.getUTCDate() : date.getDate();
return `${year}${padN(month)}${padN(dayOfMonth)}`;
}
/** #pure */
function transform (array, {
newestFirst = false,
parseDates = false,
utc = false,
} = {}) {
// Create a function for sorting dates, sorting by oldest/newest
const sortFn = createDefaultSortByObjKey('date', {reverse: newestFirst});
const sorted = array
// Create actual date objects for every date property value
.map(o => ({...o, date: new Date(o.date)}))
// Sort them
.sort(sortFn);
// This will be used to compare if the current object's date occurred
// on the same date as the previous
let lastKey = '';
// The objects will be stored in inner arrays, grouped by calendar dates
const grouped = [];
for (const obj of sorted) {
const key = getSerializedYMD(obj.date, {utc});
// Create a new inner array group if a new calendar date is encountered
if (key !== lastKey) grouped.push([]);
// Add the object to the current date group
grouped.at(-1).push(obj);
// Update the last key
lastKey = key;
}
// Now just pick one date from each group
return grouped.map(group => {
// Pick the oldest/newest object in the group
const obj = group.at(newestFirst ? 0 : -1);
return parseDates
// Return it directly with the date value as an actual date object
? obj
// Or convert the date back to an ISO string first
: {...obj, date: obj.date.toISOString()};
});
}
const input = {
name: 'xy',
lastname: 'yx',
history: [
{ value: 0.02, date: '2022-08-02T23:03:22.895Z' },
{ value: 0.04, date: '2022-08-02T22:03:16.603Z' },
{ value: 0.08, date: '2022-08-02T21:03:20.378Z' },
{ value: 0.02, date: '2022-08-01T23:03:32.584Z' },
{ value: 0.04, date: '2022-08-01T22:03:30.311Z' },
],
};
const result = {
// Spread in all of the other properties
...input,
// And add a new transformed array from the `history` property
newHistory: transform(input.history, {newestFirst: true, utc: true}),
// You can even use the sorting function to sort the original history if you want:
// history: [...input.history].sort(createDefaultSortByObjKey('date', {reverse: true})),
};
console.log(result);
// You could have also used the options to get a different result variation:
// transform(input.history, {
// newestFirst: false,
// parseDates: true,
// utc: false,
// });

How to add new value inside array of object by id (not new item)

I'm trying add a new value inside my array by id. I'm not trying add a new item in my array... For this I can use push(), but it add new item not a new value.
I'm trying do it:
My array:
const data =
[
{
"id": 1,
"year":2019,
"value": 2,
},
{
"id": 2,
"year": 2019,
"value": 89,
},
{
"id": 3,
"year": 2019,
"value": 99,
}
]
Inside an especific id I would to add a new value like this:
data.forEach(item => {
if(item.id === 2){
//data inside id 2 -> item: 55
}
})
So my new dataarray looks like this:
const data =
[
{
"id": 1,
"year":2019,
"value": 2,
},
{
"id": 2,
"year": 2019,
"value": 89,
"item": 55
},
{
"id": 3,
"year": 2019,
"value": 99,
}
]
In most of my searches, I found just how to add a new element. But this I know how to do (push()).
So how to add a new value inside specified id?
Just assign the property you want to add:
data.forEach(item => {
if(item.id === 2){
item.item = 55;
}
})
If the IDs are unique, you can use the .find() method:
var el = data.find(item => item.id === 2);
if (el) {
el.item = 55;
}
try
data.find(x=> x.id==2).item=55;
const data =
[
{
"id": 1,
"year":2019,
"value": 2,
},
{
"id": 2,
"year": 2019,
"value": 89,
},
{
"id": 3,
"year": 2019,
"value": 99,
}
]
data.find(x=>x.id==2).item=55;
console.log(data);
You can iterate and assign value based on your criteria
data.map(function(x){
if(x.id == 2){
x.value = 100;
}
})
You can implement method using Array.find to avoid unnecessary iterations:
const array = [
{
"id": 1,
"year":2019,
"value": 2,
},
{
"id": 2,
"year": 2019,
"value": 89,
},
{
"id": 3,
"year": 2019,
"value": 99,
}
];
const changeValue = (array, id, field, value) =>
array.find(el => el.id === id)[field] = value;
changeValue(array, 1, 'year', 9999);
console.log('result: ', array);
You have an array of objects and you want to add a field to one of the objects. So, first, you have to find the object you want to change. Array items can be accessed by index, but you don't know the index. There are several methods to find an item in an array.
var item = data.find(function(d, i){
return item.id === 2; //criteria
});
or in ES6 syntax:
var item = data.find(d=>d.id == 2);
after that, you can change item the way you want.
item.anotherField = 'another value';
As you said, push() adds an item to the array. It doesn't change existing items in the array.
Your code is more or less right there. To set the property of an item, you can do either object.propertyName = ... or object["propertyName"] = ....
With that, you'd simply need to update your example to look like this:
data.forEach(item => {
if(item.id === 2){
item.item = 55; //data inside id 2 -> item: 55
}
})
As a more efficient alternative, consider Array.find(). It won't continue to loop through the array after it finds the id, whereas your forEach will always loop through the array in its entirety.
const data = [ { "id": 1, "year":2019, "value": 2, }, { "id": 2, "year": 2019, "value": 89, }, { "id": 3, "year": 2019, "value": 99, } ];
( data.find(({id})=> id === 2) || {} ).item = 55;
console.log(data);
You'll notice I've followed the .find() with || {}. This is simply so that if an item with id === 2 isn't found, attempting to set the property won't throw an error.

Sort array by child's child

The situation is: I have an array of objects, in which every object has an array of objects. The array looks like this:
[
{
"dislikes": [
{
"createDate": {
"date": 11,
"day": 0,
"hours": 18,
"minutes": 15,
"month": 10,
"seconds": 11,
"time": 1541956511001,
"timezoneOffset": -60,
"year": 118
},
},
{
"createDate": {
"date": 11,
"day": 0,
"hours": 18,
"minutes": 15,
"month": 10,
"seconds": 11,
"time": 1541956511008,
"timezoneOffset": -60,
"year": 118
},
}
],
},
{
"dislikes": [
{
"createDate": {
"date": 11,
"day": 0,
"hours": 18,
"minutes": 15,
"month": 10,
"seconds": 11,
"time": 1541956511011,
"timezoneOffset": -60,
"year": 118
},
},
{
"createDate": {
"date": 11,
"day": 0,
"hours": 18,
"minutes": 15,
"month": 10,
"seconds": 11,
"time": 1541956511028,
"timezoneOffset": -60,
"year": 118
},
}
],
}
]
So I want to sort the users, and the dislikes by the time in their dislikes. So the user with the earliest dislike would be first, as well as the earliest dislike would be first in each users' dislikes array. I believe I have to do multiple sorts, but how can I do that exactly?
You can map the items and add a property to it containing the earliest dislike and then sort on that:
const data = [{"dislikes":[{"createDate":{"date":11,"day":0,"hours":18,"minutes":15,"month":10,"seconds":11,"time":1541956511001,"timezoneOffset":-60,"year":118}},{"createDate":{"date":11,"day":0,"hours":18,"minutes":15,"month":10,"seconds":11,"time":1541956511008,"timezoneOffset":-60,"year":118}}]},{"dislikes":[{"createDate":{"date":11,"day":0,"hours":18,"minutes":15,"month":10,"seconds":11,"time":1541956511011,"timezoneOffset":-60,"year":118}},{"createDate":{"date":11,"day":0,"hours":18,"minutes":15,"month":10,"seconds":11,"time":1541956511028,"timezoneOffset":-60,"year":118}}]}];
console.log(
data
//map and add newestDislike property
.map((d) => ({
...d,
//reduce and only takes the lowest time value
newestDislike: (d.dislikes || []).reduce(
(result, item) =>
item.createDate.time < result
? item.createDate.time
: result,
Infinity, //defaults to infinity (if no dislikes)
),
}))
.sort((a, b) => a.newestDislike - b.newestDislike),
);
If the dislikes in the user are already sorted by oldest date first then you can skip the map and reduce part. If a user can have empty dislikes or undefined then make sure you use a getter function with a default so your code won't crash:
//gets a nested prop from object or returns defaultValue
const get = (o = {}, path, defaultValue) => {
const recur = (o, path, defaultValue) => {
if (o === undefined) return defaultValue;
if (path.length === 0) return o;
if (!(path[0] in o)) return defaultValue;
return recur(o[path[0]], path.slice(1), defaultValue);
};
return recur(o, path, defaultValue);
};
console.log(
data.sort(
(a, b) =>
get(
a,
['dislikes', 0, 'createDate', 'time'],
Infinity,
) -
get(
b,
['dislikes', 0, 'createDate', 'time'],
Infinity,
),
),
);
//Supply the array you've metioned as the argument users to the below method, sortDislikesForAllUsers
let sortDislikesForAllUsers = function(users) {
return users.map(user => {
return {
dislikes: user.dislikes.sort((dislikeA, dislikeB) => ((dislikeA.createDate.time < dislikeB.createDate.time) ? -1 : (dislikeA.createDate.time > dislikeB.createDate.time) ? 1 : 0))
}
})
}
//Supply the array returned in the above method as input to the below method, sortUsers
let sortUsers = function(arrayOfSortedDislikesPerUser) {
return arrayOfSortedDislikesPerUser.sort((userA, userB) => ((userA.dislikes[0].createDate.time < userB.dislikes[0].createDate.time) ? -1 : (userA.dislikes[0].createDate.time > userB.dislikes[0].createDate.time) ? 1 : 0))
}
let arrayOfSortedDislikesPerUser = sortDislikesForAllUsers(users);
let finalSortedArray = sortUsers(arrayOfSortedDislikesPerUser);
console.log(finalSortedArray);
In the below snippet,
sortDislikesForAllUsers This method sorts the dislikes for individual
users
sortUsers This method sorts the users based on the first dislike time
of the sorted dislikes array obtained from the above method
Simple :)
Run the below snippet. You can directly copy paste it in your code!
let users = [{
"dislikes": [
{
"createDate": {
"date": 11,
"day": 0,
"hours": 18,
"minutes": 15,
"month": 10,
"seconds": 11,
"time": 1541956511001,
"timezoneOffset": -60,
"year": 118
},
},
{
"createDate": {
"date": 11,
"day": 0,
"hours": 18,
"minutes": 15,
"month": 10,
"seconds": 11,
"time": 1541956511008,
"timezoneOffset": -60,
"year": 118
},
}
],
},
{
"dislikes": [
{
"createDate": {
"date": 11,
"day": 0,
"hours": 18,
"minutes": 15,
"month": 10,
"seconds": 11,
"time": 1541956511011,
"timezoneOffset": -60,
"year": 118
},
},
{
"createDate": {
"date": 11,
"day": 0,
"hours": 18,
"minutes": 15,
"month": 10,
"seconds": 11,
"time": 1541956511028,
"timezoneOffset": -60,
"year": 118
},
}
],
}]
let sortDislikesForAllUsers = function(users) {
return users.map(user => {
return {
dislikes: user.dislikes.sort((dislikeA, dislikeB) => ((dislikeA.createDate.time < dislikeB.createDate.time) ? -1 : (dislikeA.createDate.time > dislikeB.createDate.time) ? 1 : 0))
}
})
}
let sortUsers = function(arrayOfSortedDislikesPerUser) {
return arrayOfSortedDislikesPerUser.sort((userA, userB) => ((userA.dislikes[0].createDate.time < userB.dislikes[0].createDate.time) ? -1 : (userA.dislikes[0].createDate.time > userB.dislikes[0].createDate.time) ? 1 : 0))
}
let arrayOfSortedDislikesPerUser = sortDislikesForAllUsers(users);
let finalSortedArray = sortUsers(arrayOfSortedDislikesPerUser);
console.log(finalSortedArray);
EDIT: WRT to the comment by #HMR:
1. It mutates the original array. Yes. If you want to avoid mutation, you must create a copy of the sent array.
let noRefCopy = new Array()
noRefCopy = noRefCopy.concat(originalArr)
Now, perform sorting on the copy and return the same.
2. If you wanna have checks for undefined etc, sure you can.
The above answer attempts to address the logic. Sure we can address the above 2 concerns if the question is really specific to them.
Cheers,
Kruthika
Check the code below. This will let you sort based on time:
function sortByTime(obj1, obj2){
return obj1.time - obj2.time;
}
array.sort((obj1, obj2)=>{
obj1.dislikes.sort(sortByTime);
obj2.dislikes.sort(sortByTime);
return obj1.dislikes[0].time - obj2.dislikes[0].time;
});
I did not get what you meant by earliest time. The above code sorts time in ascending order.
NOTE: The above code does not handle edge cases where a property night be missing
Something like as follows (with lodash.js)
_.each(users, (u) => { u.dislikes = _.sortBy(u.dislikes, 'createdDate.time'); });
users = _.sortBy(users, 'dislikes[0].createdDate.time');

Javascript underscore data format array of object

By using underscoreJS lib and manipulating some datas, i have this object
var data = {
"2017-09-26": [
{
"id": 274281,
"value": 10
},
{
"id": 274282,
"value": 20
}],
"2017-09-27": [
{
"id": 274281,
"value": 12
},
{
"id": 274282,
"value": 13
}],
}
i would like to obtain this result below by passing the keys as date in the child object and transform the value of id key as the new key of the value of value
var data = [{
date:"2017-09-26",
274281: 10,
274282: 20
},
{
date:"2017-09-27",
274281: 12,
274282: 13
}]
Please does someone as an idea to help me to do this and ideally efficiently?
Thanks
Here it is in one line:
Object.keys(data).map(key => ({date: key, ...data[key].reduce((p, c) => {p[c.id] = c.value; return p}, {})}))
Result:
[{
"274281":10,
"274282":20,
"date":"2017-09-26"
},
{
"274281":12,
"274282":13,
"date":"2017-09-27"
}]
You need nested loops. The first level creates the objects with the date property, then you loop over the objects in that value, and add the id: value properties to the result.
var newdata = _.map(data, (date, objects) => {
res = {date: date};
_.each(objects, obj => {
res[obj.id] = obj.value;
});
return res;
});
You can use Array.from() on the result of Object.entries(data) to create an array of objects by passing a callback function as the second argument.
Then for each sub-array, use .reduce() to create a new object from its members.
var data = {
"2017-09-26": [
{ "id": 274281, "value": 10 },
{ "id": 274282, "value": 20 }
],
"2017-09-27": [
{ "id": 274281, "value": 12 },
{ "id": 274282, "value": 13 }
],
};
const result = Array.from(Object.entries(data), ([key, arr]) =>
arr.reduce((res, {id, value}) =>
Object.assign(res, {[id]: value})
, {date: key})
);
console.log(result);
Here's one that's just about the same, but uses the new object literal spread syntax.
var data = {
"2017-09-26": [
{ "id": 274281, "value": 10 },
{ "id": 274282, "value": 20 }
],
"2017-09-27": [
{ "id": 274281, "value": 12 },
{ "id": 274282, "value": 13 }
],
};
const result = Array.from(Object.entries(data), ([key, arr]) =>
({date: key,
...Object.assign({}, ...arr.map(({id, value}) => ({[id]: value})))
})
);
console.log(result);

Create JSON with data from database and JavaScript generated

I need to create a calendar view with fullcalendar.io. For some dates, I have a specific price in my database and I retrieve it, but for some dates (without specific prices) I need to put the usual rates in the objects I need to create with JavaScript. Problem is now because I don't know how to make JSON for that.
In short: I need to have a price for every date, but for some dates I get data from database. How do I create such JSON objects in JavaScript?
I have this code:
var db_data = [
{
"id": 5,
"user_id": 1,
"article_id": 5,
"title": "",
"start": "2016-03-25 15:18:46"
},
{
"id": 4,
"user_id": 1,
"article_id": 5,
"price": 55,
"title": "",
"start": "2016-03-15 15:18:46"
},
{
"id": 3,
"user_id": 1,
"article_id": 5,
"price": 35,
"title": "",
"start": "2016-03-07 15:18:46"
},
{
"id": 2,
"user_id": 1,
"article_id": 5,
"price": 22,
"title": "drugi",
"start": "2016-03-05 15:18:46"
},
{
"id": 1,
"user_id": 1,
"article_id": 5,
"price": 44,
"title": "prvi",
"start": "2016-02-04 15:18:46"
}
];
// declare variables
var period_start = new Date('2016-02-02'),
period_end = new Date('2016-03-03'),
current_date = period_start,
array_of_all_dates = [];
// Create a populated array of dates
// Create a populated array of dates
while (current_date.getTime() <= period_end.getTime()) {
array_of_all_dates.push(current_date);
current_date = new Date(+current_date);
current_date.setDate(current_date.getDate() + 1);
}
// Now loop over the array of populated dates and mutate, so something like
array_of_all_dates = array_of_all_dates.map(function (date) {
var found_in_db = db_data.filter(function (db_data) {
return new Date(db_data.start.replace(" ", "T")).getTime() === date.getTime(); // You need to do this comparison better!
});
if (found_in_db.length > 0) {
return found_in_db[0];
}
var new_object = {
title: '',
start: date,
price: '{{$article->price}}'
};
console.log(new_object);
return new_object;
});
console.log('result'+array_of_all_dates);
drawCalendar(array_of_all_dates);
And with this code I get data from database and dates (start) which are not excist in database I create with JavaScript.
But with this function I get this data and I can't create calendar:
I also try with this:
// Now loop over the array of populated dates and mutate, so something like
array_of_all_dates = array_of_all_dates.map(function (date) {
var found_in_db = db_data.filter(function (db_data) {
var db_data_date = new Date(db_data.start.replace(" ", "T"));
return db_data_date.getFullYear() === date.getFullYear() &&
db_data_date.getMonth() === date.getMonth() &&
db_data_date.getDay() === date.getDay();
});
if (found_in_db.length > 0) {
return found_in_db[0];
}
var new_object = {
a_property: 'some_default_value',
start: date
};
console.log(new_object);
return new_object;
});
But currently I get this:
I don't see how this:
new Date(db_data.start.replace(" ", "T")).getTime() === date.getTime()
can ever be true. The dates in db_data have a time set in them "2016-03-15 15:18:46", but the dates you create in array_of_all_dates do not Date('2016-02-02').
Your second date comparison seems to work, but I am unclear what it is you hope to be the result of the:
array_of_all_dates.map( ... );
In some case you return an element from db_data which looks like this:
{ "id": 5", "user_id": 1, "article_id": 5, "title": "", "start": "2016-03-25 15:18:46" }
and if there was no "match" you return an object that looks like this:
{ a_property: 'some_default_value', start: date }
Note that all the original elements of array_of_all_dates are replaced by this operation.
What is it that you want to end up in array_of_all_dates so you can pass it to drawCalendar?

Categories

Resources