how to sort json array by date field - arrays

I have a JSON list of 2-D data as
var data = [
[
'Sun Feb 05 2019 00:00:00 GMT+0530 (India Standard Time)',
2,
5
],
[
'Sun Feb 06 2019 00:00:00 GMT+0530 (India Standard Time)',
5,
10
],
[
'Sun Feb 04 2019 00:00:00 GMT+0530 (India Standard Time)',
6,
2
]
];
Where the first item of each array items is a date.
I have to sort this list by date so that Feb 04 will come first while Feb 06 will come last.
How can I sort this list in JSON?

Create a Date object then compare the milliseconds: new Date(date).getTime()
const data = [
['Sun Feb 05 2019 00:00:00 GMT+0530 (India Standard Time)', 2, 5],
['Sun Feb 06 2019 00:00:00 GMT+0530 (India Standard Time)', 5, 10],
['Sun Feb 04 2019 00:00:00 GMT+0530 (India Standard Time)', 6, 2]
];
data.sort((a, b) => {
return new Date(a[0]).getTime() - new Date(b[0]).getTime();
});
console.log(data);

Related

how to take only times from dates inside array in rails

so... i need to take times from dates inside Array
so for example I have an array like this
a = [
Thu, 17 Mar 2022 10:00:00.000000000 KST +09:00,
Thu, 17 Mar 2022 10:00:00.000000000 KST +09:00,
Thu, 17 Mar 2022 14:00:00.000000000 KST +09:00,
Thu, 17 Mar 2022 14:00:00.000000000 KST +09:00,
Thu, 17 Mar 2022 17:00:00.000000000 KST +09:00]
and wanted to have result of
a = ["10:00", "10:00", "14:00", "14:00", "17:00"]
So i was trying this
can_choose =[];
a.each_with_index do |time| strftime("%H:%M")
can_choose <<|time|
but doesn't works at all...
where should I have to fix??
You can also extract the year, month, day the same way
https://ruby-doc.org/stdlib-3.1.1/libdoc/date/rdoc/Date.html
a = [
'Thu, 17 Mar 2022 10:00:00.000000000 KST +09:00',
'Thu, 17 Mar 2022 10:00:00.000000000 KST +09:00',
'Thu, 17 Mar 2022 14:00:00.000000000 KST +09:00',
'Thu, 17 Mar 2022 14:00:00.000000000 KST +09:00',
'Thu, 17 Mar 2022 17:00:00.000000000 KST +09:00']
can_choose =[]
a.map do |time|
t = DateTime.parse(time)
can_choose << t.strftime("%k:%M")
end
p can_choose
=> ["10:00", "10:00", "14:00", "14:00", "17:00"]
Ruby is all about message passing. The syntax to send a message is:
receiver.message(argument)
strftime is such message, but it needs a proper receiver. So if you have some Time instance, e.g.:
time = Time.parse('2022-03-17 10:00:00 +0900')
you'd write:
time.strftime('%H:%M') #=> "10:00"
with time being the receiver, strftime being the message and '%H:%M' being the argument.
You can use the above code in an each loop like this:
can_choose = []
a.each do |time|
can_choose << time.strftime('%H:%M')
end
Or you could use map to convert your array to another array:
can_choose = a.map { |time| time.strftime('%H:%M') }
The curly braces here { ... } are equivalent to the do ... end block above.
I would simple go with:
can_choose = a.map { |datetime| datetime.strftime('%H:%M') }
If you need only hours and minutes in 24h format, just use %R directive with Time#strftime or DateTime#strftime
can_choose = a.map { |time| time.strftime('%R') }

Angular - Pushing elements into an array in a loop updates all the preexisting values of the array with the new value

I am pushing the dates of the week into an array.
If you can refer the code, in the // good value line
The array has the correct value
But each time the dates.setDate(dates.getDate() + 1 );
executes
All the array values are automatically updated with the new value.
Instead of just pushing the new element in the array, it pushes the new element in the array and replaces all the elements of the array with the new element
this.mondayDate = this.getMonday(this.viewDate);
let dates = this.mondayDate;
this.datesOfTheWeek = [];
this.datesOfTheWeek.push(this.mondayDate);
console.log(this.datesOfTheWeek);
for(let i in [1,2,3,4,5,6]){
console.log(this.datesOfTheWeek); // good value in the array
dates.setDate(dates.getDate() + 1 );
console.log(this.datesOfTheWeek); // bad value in the array
this.datesOfTheWeek.push(dates);
console.log(this.datesOfTheWeek);
}
console.log(this.datesOfTheWeek);
1st iteration: //contains only monday date- output from //bad value
Array(1) [Tue May 21 2019 15:17:46 GMT+0200 (heure d’été d’E…]
2nd iteration: // pushing tuesday date- output from //bad value
Array(2) [Wed May 22 2019 15:17:46 GMT+0200 (heure d’été d’E…, Wed May 22 2019 15:17:46 GMT+0200 (heure d’été d’E…]
The array value at the end is
Array(6) [Sun May 26 2019 15:17:46 GMT+0200 (heure d’été d’E…, Sun May 26 2019 15:17:46 GMT+0200 (heure d’été d’E…, Sun May 26 2019 15:17:46 GMT+0200 (heure d’été d’E…, Sun May 26 2019 15:17:46 GMT+0200 (heure d’été d’E…, Sun May 26 2019 15:17:46 GMT+0200 (heure d’été d’E…, Sun May 26 2019 15:17:46 GMT+0200 (heure d’été d’E…]
But it should contain the dates from may 20 to may 26
That's because dates looks to be a Date object, not a primitive (so, if you mutate it, all the references to it will point to the mutated value). You need to create a copy: instead of
dates.setDate(dates.getDate() + 1 );
console.log(this.datesOfTheWeek); // bad value in the array
this.datesOfTheWeek.push(dates);
do something like
let newDate = new Date(dates);
newDate.setDate(dates.getDate() + 1 );
console.log(this.datesOfTheWeek);
this.datesOfTheWeek.push(newDate);

Retrieving an array of subdcuments (MEAN stack)

I have a very concrete question.
So I am querying my database using the following (Mongoose call in NodeJS with express):
UserProfileModel.find({'username': req.query.username},'progressmanual' ,function (err, entries) {
console.log("entries from the server:"+entries);
res.json(entries);
});
And this query produces the following result:
{ _id: 5580edc16f5d5c3411f703c8,
progressmanual:[ { Date: Tue Jun 16 2015 23:47:36 GMT-0400 (Eastern Daylight Time), cups: 5, miles: 5, steps: 6, duration: 6, _id: 5580edd86f5d5c3411f703c9 },
{ Date: Tue Jun 16 2015 23:47:41 GMT-0400 (Eastern Daylight Time), cups: 754, miles: 57457, steps: 457547, duration: 54745745, _id: 5580eddd6f5d5c3411f703ca },
{ Date: Tue Jun 16 2015 23:47:45 GMT-0400 (Eastern Daylight Time), cups: 547457, miles: 536346, steps: 4436346, duration: 466, _id: 5580ede16f5d5c3411f703cb },
{ Date: Tue Jun 16 2015 23:47:50 GMT-0400 (Eastern Daylight Time), cups: 436, miles: 6436, steps: 4464346, duration: 446, _id: 5580ede66f5d5c3411f703cc },
{ Date: Tue Jun 16 2015 23:49:36 GMT-0400 (Eastern Daylight Time), cups: 5, miles: 5, steps: 6, duration: 6, _id: 5580ee506f5d5c3411f703cd } ], personalgoals: {} }
On my front end I am trying to display the entries from the progressmanual
so when I try to to do res.json(entries.progressmanual) it results in null. Do you know how to extract the array of progressmanual objects?
Also, do you know why the query result contains extra "columns" that I didn't request (stuff besides progressmanual)?
Thanks to Kevin B from the comments I figured out the problem: changing find() to findOne allowed me to obtain entries.progressmanual. So it looks like find() always returns arrays so with find() I should have used entries[0].progressmanual

Find the most recent date from an Array

How to find the most recent date from an array like the one below?
Tue Jun 2 17:59:54 GMT+0200 2013
Tue Jun 5 18:00:10 GMT+0200 2013
Tue Jun 1 12:27:14 GMT+0200 2013
Tue Jun 3 17:26:58 GMT+0200 2013
Tue Jun 9 17:27:49 GMT+0200 2013
Tue Jun 1 13:27:39 GMT+0200 2015
Tue Jun 3 12:27:59 GMT+0200 2013
Tue Jun 6 15:27:22 GMT+0200 2014
Tue Jun 2 17:27:30 GMT+0200 2014
Assuming your array is full of AS3 native Date objects, you could simply do this:
array.sortOn("time",Array.DESCENDING);
trace("Most Recent:",array[0]);
You cannot use array.sort (unless you use the Array.NUMERIC flag) because it will sort the string representation of the date. So all your days of the week would then be grouped together instead of the actual date.
If your dates are strings, then you will need to convert them to Date objects prior to sorting:
//assuming your posted array is in a var called 'stringArray'
var dateArray:Array = []; //a new array to hold the converted strings
for(var i:int=0;i<stringArray.length;i++){
dateArray.push(new Date(stringArray[i]));
}
dateArray.sortOn("time",Array.DESCENDING);
trace("Most Recent Date:",dateArray[0]);
To show this in a concrete example, here is your posted dates - copy paste this code to produce the same results:
var arr:Array = new Array(
new Date("Tue Jun 2 17:59:54 GMT+0200 2013"),
new Date("Tue Jun 5 18:00:10 GMT+0200 2013"),
new Date("Tue Jun 1 12:27:14 GMT+0200 2013"),
new Date("Tue Jun 3 17:26:58 GMT+0200 2013"),
new Date("Tue Jun 9 17:27:49 GMT+0200 2013"),
new Date("Tue Jun 1 13:27:39 GMT+0200 2015"),
new Date("Tue Jun 3 12:27:59 GMT+0200 2013"),
new Date("Tue Jun 6 15:27:22 GMT+0200 2014"),
new Date("Tue Jun 2 17:27:30 GMT+0200 2014")
);
arr.sort(Array.DESCENDING);
trace("SORT:");
traceDates();
arr.sortOn("time",Array.DESCENDING);
trace("\nSORT ON:");
traceDates();
function traceDates(){
for(var i:int=0;i<arr.length;i++){
trace(" ",arr[i].fullYear + "-" + arr[i].month + "-" + arr[i].day);
}
}
//OUTPUT:
/*
SORT:
2013-5-3
2013-5-0
2013-5-0
2013-5-6
2013-5-1
2013-5-1
2014-5-1
2015-5-1 //most recent date, second to LAST item in the array
2014-5-5
SORT ON:
2015-5-1 //June 1st is the most recent date (first item in the array)
2014-5-5
2014-5-1
2013-5-0
2013-5-3
2013-5-1
2013-5-1
2013-5-0
2013-5-6
*/
Are they Date objects?
If so, you can compare the time property of each. It will give you the number of milliseconds since Jan 1, 1970. The highest number will be the most recent.
Something along these lines:
var mostRecentDate:Date = dateArray[0];
for(var i:int = 0; i < dateArray.length; i++){
if(dateArray[i].time > mostRecentDate.time){
mostRecentDate = dateArray[i];
}
}
Date objects act like simple Number when it comes to sorting or comparison. All you have to do is treat them like Numbers. So taken from Cadin answer:
dateArray.sort();
var oldestDate:Date = dateArray[0];
Will get you the oldest Date while:
dateArray.sort(Array.DESCENDING);
var mostRecentDate:Date = dateArray[0];
Will get you the most recent one.
For LDMS, this is what I got:
var firstdate:Date = new Date();
var seconddate:Date = new Date();
var thirddate:Date = new Date();
seconddate.time = firstdate.time + 5000000;
thirddate.time = firstdate.time + 50000000;
trace(seconddate > firstdate)//true
trace(firstdate > seconddate)//false
trace(seconddate.time > firstdate.time)//true
var array:Array = [thirddate, firstdate, seconddate];
trace(array)
//Wed Jun 3 03:37:40 GMT-0400 2015,Tue Jun 2 13:44:20 GMT-0400 2015,Tue Jun 2 15:07:40 GMT-0400 2015
array.sort();
trace(array)
//Tue Jun 2 13:44:20 GMT-0400 2015,Tue Jun 2 15:07:40 GMT-0400 2015,Wed Jun 3 03:37:40 GMT-0400 2015
array.sort(Array.DESCENDING);
trace(array)
//Wed Jun 3 03:37:40 GMT-0400 2015,Tue Jun 2 15:07:40 GMT-0400 2015,Tue Jun 2 13:44:20 GMT-0400 2015
Sort the array and grab the first (descending) or last (ascending) element.
Edit: 2 down-votes because I didn't provide an example, or because people don't know you can sort dates? This works:
var dates:Array = [
"Tue Jun 2 17:59:54 GMT+0200 2013",
"Tue Jun 5 18:00:10 GMT+0200 2013",
"Tue Jun 1 12:27:14 GMT+0200 2013",
"Tue Jun 3 17:26:58 GMT+0200 2013",
"Tue Jun 9 17:27:49 GMT+0200 2013",
"Tue Jun 1 13:27:39 GMT+0200 2015",
"Tue Jun 3 12:27:59 GMT+0200 2013",
"Tue Jun 6 15:27:22 GMT+0200 2014",
"Tue Jun 2 17:27:30 GMT+0200 2014"
].map(function(s:String, i:int, a:Array):Date {
return new Date(s);
}).sort(Array.NUMERIC | Array.DESCENDING);
var latest:Date = dates[0]; // Mon Jun 1 07:27:39 GMT-0400 2015
The problem is the OP did not make it clear what kind of data they are working with (strings or Date objects) so the exact solution code is unknown.

Using Arrays in Rabl

I am returning a collection from the query. The query is in this thread.
So my result is like below in my log:
[{"id"=>1, "name"=>"ASP.NET-WebForms", "description"=>"", "record_status"=>1, "created_by"=>1, "updated_by"=>1, "created_at"=>Thu, 23 Apr 2015 06:04:18 UTC +00:00, "updated_at"=>Thu, 23 Apr 2015 06:04:18 UTC +00:00, "skill_type"=>"Serverside-Framework", :assigned=>true}, {"id"=>2, "name"=>"ASP.NET-MVC", "description"=>"", "record_status"=>1, "created_by"=>1, "updated_by"=>1, "created_at"=>Thu, 23 Apr 2015 06:05:01 UTC +00:00, "updated_at"=>Thu, 23 Apr 2015 06:05:01 UTC +00:00, "skill_type"=>"Serverside-Framework", :assigned=>true}, {"id"=>3, "name"=>"RUBY-ON-RAILS", "description"=>"", "record_status"=>1, "created_by"=>1, "updated_by"=>1, "created_at"=>Thu, 23 Apr 2015 06:05:20 UTC +00:00, "updated_at"=>Thu, 23 Apr 2015 06:05:20 UTC +00:00, "skill_type"=>"Serverside-Framework", :assigned=>false}, {"id"=>4, "name"=>"C#", "description"=>"", "record_status"=>1, "created_by"=>1, "updated_by"=>2, "created_at"=>Thu, 23 Apr 2015 06:05:57 UTC +00:00, "updated_at"=>Thu, 23 Apr 2015 06:12:02 UTC +00:00, "skill_type"=>"Language", :assigned=>false}, {"id"=>5, "name"=>"Ruby", "description"=>"", "record_status"=>1, "created_by"=>1, "updated_by"=>1, "created_at"=>Thu, 23 Apr 2015 06:07:43 UTC +00:00, "updated_at"=>Thu, 23 Apr 2015 06:07:43 UTC +00:00, "skill_type"=>"Language", :assigned=>true}, {"id"=>6, "name"=>"VB", "description"=>"", "record_status"=>1, "created_by"=>1, "updated_by"=>1, "created_at"=>Thu, 23 Apr 2015 06:08:15 UTC +00:00, "updated_at"=>Thu, 23 Apr 2015 06:08:15 UTC +00:00, "skill_type"=>"Language", :assigned=>false}, {"id"=>7, "name"=>"SQL-Server", "description"=>"", "record_status"=>1, "created_by"=>1, "updated_by"=>1, "created_at"=>Thu, 23 Apr 2015 06:08:32 UTC +00:00, "updated_at"=>Thu, 23 Apr 2015 06:08:32 UTC +00:00, "skill_type"=>"DBMS", :assigned=>false}, {"id"=>8, "name"=>"MySQL", "description"=>"", "record_status"=>1, "created_by"=>1, "updated_by"=>1, "created_at"=>Thu, 23 Apr 2015 06:08:49 UTC +00:00, "updated_at"=>Thu, 23 Apr 2015 06:08:49 UTC +00:00, "skill_type"=>"DBMS", :assigned=>false}, {"id"=>9, "name"=>"Oracle", "description"=>"", "record_status"=>1, "created_by"=>1, "updated_by"=>1, "created_at"=>Thu, 23 Apr 2015 06:09:01 UTC +00:00, "updated_at"=>Thu, 23 Apr 2015 06:09:01 UTC +00:00, "skill_type"=>"DBMS", :assigned=>false}]
I think this is an array instead of an object collection. So how can I display this as json using rabl. The collection #technical_skills is not working.
My expected output is:
{
"domain_skill": {
"id": 1,
"name": "domain name",
"description": "some description text",
"technical_skills": [
{
"id": 1,
"name": "ASP.NET-WebForms",
"assigned": true
},
{
"id": 2,
"name": "ASP.NET-MVC",
"assigned": true
}
]
}
}
Edit:
I got that this is a json array. My method to merge another field so that I can convert this to json and merge the new fields. Now I thought this is json array. Please check my controller method below:
id = params[:id]
#domain_skill_technical_skill_ids = DomainSkillsTechnicalSkill.select('id, technical_skill_id').where(domain_skill_id: id).collect(&:technical_skill_id)
Rails.logger.info(#domain_skill_technical_skill_ids.to_a)
#technical_skills = []
TechnicalSkill.select('id, name').where(record_status: 1).each do |skill|
#technical_skills << skill.as_json.merge!(
{ assigned: #domain_skill_technical_skill_ids.include?(skill.id)}
)
end
#domain_skill_view_model = DomainSkillViewModel.new(#domain_skill, #technical_skills)
respond_with #domain_skill_view_model
My rabl:
object :#domain_skill_view_model
object :#domain_skill
attributes :id, :name, :description
node :technical_skills do
#technical_skills.each do |skill|
end
end

Resources