How to order array objects by date? - javascript

I have an array of objects like this
layerArr = [
{
name: "layer 1"
layerDate: "/Date(6958748400000)/"
layerDateFormatted: "31 December 2018"
etc...
}
{
name: "layer 2"
layerDate: "/Date(9375937500000)/"
layerDateFormatted: "23 December 2017"
etc...
}
{
name: "layer 3"
layerDate: "/Date(1554764400000)/"
layerDateFormatted: "15 January 2018"
etc...
}]
How can I sort layerArr by date with the latest date first?
In this example, when layer 2 is sorted correctly, I also want the latest date to become layer 1 and the oldest date should become the last layer. (the example above is made up values)
Thanks
EDIT: the links suggested to other threads do not explain how to change "name" so that the latest date becomes name ="layer 1" all the way to the oldest date becoming the last layer.

Use Array.sort():
layerArr = [
{ name: "layer 1", layerDate: "/Date(6958748400000)/", layerDateFormatted: "31 December 2018" },
{ name: "layer 2", layerDate: "/Date(9375937500000)/", layerDateFormatted: "23 December 2017" },
{ name: "layer 3", layerDate: "/Date(1554764400000)/", layerDateFormatted: "15 January 2018" }
];
sortedLayerArr = layerArr.sort(function(a, b) {
return new Date(a.layerDateFormatted)- new Date(b.layerDateFormatted);
}).map((layer, index) => ({
...layer,
name: `layer ${index + 1}`,
}));
console.log(layerArr);
console.log(sortedLayerArr);

Related

Displaying Fetched date in a custom calendar React native

So basically i created a custom calendar for my doctor Appointement App that looks like this:
it displays the current week and date of the days.
till now those time slot are a static array that i made and rendered in a flatlist:
this.state = {
timeList: [
{ id: 1, time: "08:00 am" },
{ id: 2, time: "09:00 am" },
{ id: 3, time: "10:00 am" },
{ id: 4, time: "11:00 am" },
{ id: 5, time: "12:00 pm" },
{ id: 6, time: "01:00 pm" },
{ id: 7, time: "02:00 pm" },
{ id: 8, time: "03:00 pm" },
{ id: 9, time: "04:00 pm" },
{ id: 10, time: "05:00 pm" },
{ id: 11, time: "06:00 pm" },
{ id: 12, time: "07:00 pm" },
{ id: 13, time: "08:00 pm" }
]
};
and:
<FlatList
data={this.state.timeList}
renderItem={({ item, index }) => this.renderTimeData(item, index)}
keyExtractor={(item, index) => index.toString()}
/>
So my problem is i want to render the time from a fetched data in a way that take into consideration the the date of the day.for instance, here is a log of the data:
so from that attribut "date_start" i should make sure the date is matching in my calendar so i can display that "9:30"
Any idea how can I approach it?
i hope i made my self clear enough and thank you for your suggestions
You can simply use a library like Moment to identify the date & time of your object as below,
let date = moment("2020-03-23 09:30").format('YYYY-MM-DD');
console.log(date)
let time = moment("2020-03-23 09:30").format('h:mm A');
console.log(time)
For more information check String format of Moment.
Hope this helps you. Feel free for doubts.
If you want to allow the user to choose date and time for a day the official react-native documentation recommend you to use DateTimePicker
With this you will have the native component for rendering date in IOS and Android.

How to get the address of a location from a google maps URL?

Given a URL of a google maps location, I want to be able to get the address of the location.
For example given this URL:
https://www.google.com/maps/place/Eiffel+Tower/#48.8583701,2.2922926,17z/data=!3m1!4b1!4m5!3m4!1s0x47e66e2964e34e2d:0x8ddca9ee380ef7e0!8m2!3d48.8583701!4d2.2944813
I want to get its address:
Champ de Mars, 5 Avenue Anatole France, 75007 Paris, France
Any ideas of how I can do this? I have looked into the google maps API but have not found a way of achieving this.
If you look at the sample URL
https://www.google.com/maps/place/Torre+Eiffel/#48.8583701,2.2922926,17z/data=!3m1!4b1!4m5!3m4!1s0x47e66e2964e34e2d:0x8ddca9ee380ef7e0!8m2!3d48.8583701!4d2.2944813
carefully, you will note the following code after '!1s' and before '!8m2':
0x47e66e2964e34e2d:0x8ddca9ee380ef7e0.
This code is the feature id of the place. You can extract this code from the URL using regexp for example. After that you can split the code by ':' and use the second part (0x8ddca9ee380ef7e0) in place details request with parameter cid. Note that this parameter is not publicly documented, but at the moment of writing this undocumented parameter works as expected.
Execute the following request
https://maps.googleapis.com/maps/api/place/details/json?cid=0x8ddca9ee380ef7e0&key=YOUR_API_KEY
You will get the following response
{
html_attributions: [ ],
result: {
address_components: [
{
long_name: "Champ de Mars",
short_name: "Champ de Mars",
types: [
"point_of_interest",
"establishment"
]
},
{
long_name: "5",
short_name: "5",
types: [
"street_number"
]
},
{
long_name: "Avenue Anatole France",
short_name: "Avenue Anatole France",
types: [
"route"
]
},
{
long_name: "Paris",
short_name: "Paris",
types: [
"locality",
"political"
]
},
{
long_name: "Arrondissement de Paris",
short_name: "Arrondissement de Paris",
types: [
"administrative_area_level_2",
"political"
]
},
{
long_name: "Île-de-France",
short_name: "Île-de-France",
types: [
"administrative_area_level_1",
"political"
]
},
{
long_name: "France",
short_name: "FR",
types: [
"country",
"political"
]
},
{
long_name: "75007",
short_name: "75007",
types: [
"postal_code"
]
}
],
adr_address: "Champ de Mars, <span class="street-address">5 Avenue Anatole France</span>, <span class="postal-code">75007</span> <span class="locality">Paris</span>, <span class="country-name">France</span>",
formatted_address: "Champ de Mars, 5 Avenue Anatole France, 75007 Paris, France",
formatted_phone_number: "0 892 70 12 39",
geometry: {
location: {
lat: 48.85837009999999,
lng: 2.2944813
},
viewport: {
northeast: {
lat: 48.8597461302915,
lng: 2.29610765
},
southwest: {
lat: 48.85704816970851,
lng: 2.29251745
}
}
},
icon: "https://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png",
id: "fd0cfb424bbd79bf28a832e1764f1c2aa5927714",
international_phone_number: "+33 892 70 12 39",
name: "Eiffel Tower",
opening_hours: {
open_now: true,
periods: [
{
close: {
day: 1,
time: "0045"
},
open: {
day: 0,
time: "0900"
}
},
{
close: {
day: 2,
time: "0045"
},
open: {
day: 1,
time: "0900"
}
},
{
close: {
day: 3,
time: "0045"
},
open: {
day: 2,
time: "0900"
}
},
{
close: {
day: 4,
time: "0045"
},
open: {
day: 3,
time: "0900"
}
},
{
close: {
day: 5,
time: "0045"
},
open: {
day: 4,
time: "0900"
}
},
{
close: {
day: 6,
time: "0045"
},
open: {
day: 5,
time: "0900"
}
},
{
close: {
day: 0,
time: "0045"
},
open: {
day: 6,
time: "0900"
}
}
],
weekday_text: [
"Monday: 9:00 AM – 12:45 AM",
"Tuesday: 9:00 AM – 12:45 AM",
"Wednesday: 9:00 AM – 12:45 AM",
"Thursday: 9:00 AM – 12:45 AM",
"Friday: 9:00 AM – 12:45 AM",
"Saturday: 9:00 AM – 12:45 AM",
"Sunday: 9:00 AM – 12:45 AM"
]
},
photos: [
{
height: 408,
html_attributions: [
"Hauser Quaid Zzyzx"
],
photo_reference: "CmRaAAAAFOGpKiedFvYYu7R7qLkxqdY2GqcGqmHNPvny_a2dYV81XTFC2RL0ybS-NZg_oQUa0Fa-U178CBPLmCx8Xz_PTt16jW87WUm9rdYHoVklaAeH52pVuCwW1014vu-5EboPEhDHt-Gt9o_2tEKXWt6FQVXwGhSnNEX49VjoMdiPlXPaZ3z18yN-_A",
width: 612
},
{
height: 3888,
html_attributions: [
"Gonçalo Borralho"
],
photo_reference: "CmRaAAAAJLOe9SSk1G-d8KTm5dFPw-CAvXd7SK5eg0AS2_zF7eTsNGDJZptupKLRodFE9GfdpRcxYhTzIWkoBx2EIEPamq_A5G8A7Q905KlIkDln6Kz83xIDDjY5D4FBHCQnySriEhBRME9npMoGWKdfz2HDJnV3GhRQT2YZDE2axrCDGbWguRiYaDP4jw",
width: 2592
},
{
height: 600,
html_attributions: [
"Maria Goryunova"
],
photo_reference: "CmRaAAAAbZO6_2CHj1TxxpNu9-un01rYHMy7v7MhiWB4auCwwqp8a2xkSlWiheQZQBG6kGHp0qPkn6NNwhup9teVKZUjmPTqvMFhI5ER0WyX-RrhHFStBMa5it6qT6V7H4VI297KEhCr-hcQDRTtE0q3fEqWKlnXGhRme7pNMXQRYxuXIpJAkWtEVxQ_Mw",
width: 600
},
{
height: 4160,
html_attributions: [
"praveen dhingra"
],
photo_reference: "CmRaAAAA_WjfpbIVJ5zVIy1j-0Q2VKwxGjbGQNzcD9F6rIFEAVqQEvrv_OSrfTX3Mac8NwDopr1rl63jZGUbExJkQDckM-DGr9TQqfT7FTLbSxtOra6NTIa5jijTkTh-Ivw_uB1dEhCeiq5yjZZjBfRnmc2SLUxYGhQ4XOKL7PlMZpgZ_Be_b3oK8hHwIw",
width: 2080
},
{
height: 4000,
html_attributions: [
"H.İbrahim Üzmezoğlu"
],
photo_reference: "CmRaAAAAmLIY1pgIGZL720khB_lfo956P3UX_rnBZG0KxTImqJCR8sZGHXGv7IdcIM_c5kaIYLkeG-WwXehU367cLhN8ordS0lqCITaiXL2w2HdL0mABPcr3JYw4fGBsv_I4ScK-EhCJDIwwlPEel5mXVt0Ype10GhTbA4MsOMt9mVegngR7AOIjqYiX3w",
width: 3000
},
{
height: 3648,
html_attributions: [
"Kerem Enginar"
],
photo_reference: "CmRaAAAACLc5gwLJxZRPVQI-5X_iI1TyaFwc6HA1aFYeSzDAU7514FU_iEYWxVEEgpavyXmC4PU1x-NVvCSOyxBVEbcX2wgYp6dMsIgg2wK11HvlZW2OxHAVsiDv2m3Qk7hXyhApEhCiR3DSFJ8dwHtsH4OMKCuqGhRcFAIpkIp0XvhAXpHmkFRnfVcGCQ",
width: 1744
},
{
height: 3968,
html_attributions: [
"LUIS ROLDAN"
],
photo_reference: "CmRaAAAAwyx_YEdelPVTlgqw9KWqXuXKuzDRS9m6gyemO9HIIJGNSVfW-kYClF8TeKqxZt9YvSe9SnhmCMzFGr5fKeKUbiTIz0wAFNvZysdqT9TV8nJ009m-FTtB0Rx8RC0h70e5EhCIUcnE8JgPBue7IUmwOA0fGhRzbGCB5-35S34i7AIaJXu9CEE2jg",
width: 2976
},
{
height: 4032,
html_attributions: [
"Frank Rafaelsen Lian"
],
photo_reference: "CmRaAAAAFTSEd1eR_zkspc7ksK3S22nq69UXYtW8DGR7B7yfCiL2Q_IJl29yofflEj5HQ8ANuLyQR-NlSYGN3FhnC5jj-zGqUR4wTv-_B-imPEnCvq2mHDz_gO43bbc2xQmcGsecEhCR7Uryl1QTECndlU0f94uuGhT4CYw5JLAO-27Gi_cIdK9Ic1YFxA",
width: 3024
},
{
height: 3024,
html_attributions: [
"Wadih Antoun"
],
photo_reference: "CmRaAAAA6A_JRLItYa05p9NcXapox8ROY_h2id9AVewX1wChZPP8iBZvA1JHQo9qEFGwyTUuXQ9Pu7-xXgKJkgCepp2SkSdprRjBfvcmt-ZQUH4LjigupU1AAqzMZRVXKbZ2WjHgEhBAIQ2EgygtvhtZSy6Y7QJbGhTLTj0jgWPIJVTxHgUFzqWbnnnymw",
width: 4032
},
{
height: 4224,
html_attributions: [
"Steve Bird"
],
photo_reference: "CmRaAAAAGbShlT71nLeJHL5sagdgtjssvWCBhDsqPsZ9xeNXu48iFlBsRoRarZZTMUJSK0p2H91Rg27XE8HFCRvvgxLTctA9eJhCktsDoOjP33zw04sX19jrrMhGpS0kOemTV-daEhAz41RPzVtazLhOYKdmkSHqGhRPd9g9S94_N0HrxV9oRcPCHfd2ZQ",
width: 2368
}
],
place_id: "ChIJLU7jZClu5kcR4PcOOO6p3I0",
plus_code: {
compound_code: "V75V+8Q Paris, France",
global_code: "8FW4V75V+8Q"
},
rating: 4.6,
reference: "ChIJLU7jZClu5kcR4PcOOO6p3I0",
reviews: [
{
author_name: "Margaret Bagdon",
author_url: "https://www.google.com/maps/contrib/115820855361415255644/reviews",
language: "en",
profile_photo_url: "https://lh5.googleusercontent.com/-L8M8JctpleE/AAAAAAAAAAI/AAAAAAAAAAA/ACHi3reM2h_11AXwURDawihkuOG34a9MQg/s128-c0x00000000-cc-rp-mo-ba4/photo.jpg",
rating: 4,
relative_time_description: "in the last week",
text: "I purchased tickets on line for 9:00 on a Tues in June. Couldn't print my tickets because of a problem with the account so we showed up early to have them printed. We we're lucky no one was in line at the info booth. We waited in the line (30 minutes) for the time slot we booked. The line to purchase tickets was much longer so I recommend you buy in advance. We rode the glass side lift to the first observation deck and immediately got in line to go to the summit. Waited about 15 minutes. The top was crowded and we watched the sunset from the top. The views are nice so I think it was worth it. You can purchase a small glass of champagne if you want a toast at the top. We took the lift down and stopped for a drink and a rest. We walked the remainder of the way and got down in time to see the brief light show. Good view on the lawn. I would recommend stopping here if it is your first time in Paris and you don't mind heights.....be prepared to wait....and it will be crowded.....and expensive...",
time: 1563234656
},
{
author_name: "Shahrukh Naeem",
author_url: "https://www.google.com/maps/contrib/102499154519714023927/reviews",
language: "en",
profile_photo_url: "https://lh4.googleusercontent.com/-qQBtFB0REZI/AAAAAAAAAAI/AAAAAAAAAAA/ACHi3rd9bYBR5bZcH6BMYaRd5yv2Gw79WQ/s128-c0x00000000-cc-rp-mo-ba5/photo.jpg",
rating: 5,
relative_time_description: "2 weeks ago",
text: "Wonderful romantic place. Must visit with loved ones. Breathtaking view from up the level 2. People can also buy an additional Ticket and go up to the next level to even have a wonderful view or dine with love. Sure a wonder to visit and of course go on top of it. So many romantic couples were taking romantic photos in this structure. In the night there was a five minute light show which has to be viewed from a distance to enjoy how magnificently people made this city a tourist attraction because of this structure",
time: 1562399468
},
{
author_name: "Anca Chelaru",
author_url: "https://www.google.com/maps/contrib/113471456079540231282/reviews",
language: "en",
profile_photo_url: "https://lh4.googleusercontent.com/-UnNJLd9XjiM/AAAAAAAAAAI/AAAAAAAAAAA/ACHi3rcGIic0U1eWvnrKz-xfp2s6mqI2vg/s128-c0x00000000-cc-rp-mo-ba3/photo.jpg",
rating: 5,
relative_time_description: "a week ago",
text: "I loved it! It is better than Empire State Building because you see the empty space going up/down and it gives you an adrenaline rush, that you don't feel in a building. You can take the stairs on the way down, better than the elevator. At the restaurant level, there is glass floor, so you can see all the way down. The gift store at the restaurant level is better than the on on top, it has more staff. Buy the tickets online, saves time. You can easily spend here 1/2 a day.",
time: 1562661564
},
{
author_name: "Jeroen van der Linde",
author_url: "https://www.google.com/maps/contrib/109990025751819839602/reviews",
language: "en",
profile_photo_url: "https://lh5.googleusercontent.com/-g03RbnKDnJ8/AAAAAAAAAAI/AAAAAAAAAAA/ACHi3ren8G7DFs0oZV0hkiYaBdYRydQleQ/s128-c0x00000000-cc-rp-mo-ba6/photo.jpg",
rating: 5,
relative_time_description: "a week ago",
text: "Of course one of the main tourist attractions in Paris, France and even the world. Elevators work now but you can still take the stairs if you want to have a cheaper option to go up. T The direct area is fenced off with high bullet proof glass walls and protected entrances at the sides. Visitors are subject to some screening. If you are looking for pictures of the Eiffel Tower you can also visit the lawn or pond at the sides for better views.",
time: 1562921719
},
{
author_name: "Pratap Ramamoorthy",
author_url: "https://www.google.com/maps/contrib/117384906578505429183/reviews",
language: "en",
profile_photo_url: "https://lh3.googleusercontent.com/-Oo8pn66vGDM/AAAAAAAAAAI/AAAAAAAAA7g/rXZn8xS2bPg/s128-c0x00000000-cc-rp-mo-ba6/photo.jpg",
rating: 5,
relative_time_description: "a month ago",
text: "Wonderful romantic place. Must visit with loved ones. Breathtaking view from up the level 2. People can also buy an additional Ticket and go up to the next level to even have a wonderful view or dine with love. Sure a wonder to visit and of course go on top of it. So many romantic couples were taking romantic photos in this structure. In the night there was a five minute light show which has to be viewed from a distance to enjoy how magnificently people made this city a tourist attraction because of this structure.",
time: 1559894189
}
],
scope: "GOOGLE",
types: [
"premise",
"point_of_interest",
"establishment"
],
url: "https://maps.google.com/?cid=10222232094831998944",
user_ratings_total: 166537,
utc_offset: 120,
vicinity: "Champ de Mars, 5 Avenue Anatole France, Paris",
website: "http://www.toureiffel.paris/"
},
status: "OK"
}
The formatted_address field contains address you are looking for "Champ de Mars, 5 Avenue Anatole France, 75007 Paris, France".
I hope this helps!

Javascript convert object key names based on mapping

I have a javascript object that is coming from Source1 and I am unable to change its native structure or naming convention. I am using this data to feed into a 3rd party plugin to generate some chart data. This plugin however is using the key names as the identifiers on the chart and they are not descriptive or clear enough.
I am trying to run the object through a conversion function where it will change all of the key names to their defined equivalent.
Here is an example of what I am trying to do:
var obj = [{
SubmissionID: "28935",
MetaCreatedDate: "12 Mar 2018",
Program: "Brand Risk Management",
ViewedByInvestigator: "No",
},
{
SubmissionID: "28936",
MetaCreatedDate: "12 Mar 2018",
Program: "Brand Risk Management",
ViewedByInvestigator: "Yes",
}]
function convertNames(obj){
// Converted names
var map = [{
SubmissionID: 'SubmissionIdentifier',
MetaCreatedDate: 'CreationDate',
Program: 'ProgramName',
ViewedByInvestigator: 'Viewed'
}];
// Loop through the object and convert all key names to their equivalent
for(var prop in obj){
// Convert Here
}
return obj;
}
Desired Output:
[{
SubmissionIdentifier: "28935",
CreationDate: "12 Mar 2018",
ProgramName: "Brand Risk Management",
Viewed: "No",
},
{
SubmissionIdentifier: "28936",
CreationDate: "12 Mar 2018",
ProgramName: "Brand Risk Management",
Viewed: "Yes",
}]
https://jsfiddle.net/hbg4sfqh/7/
I'd combine the .map array method and a function to convert your key names to get the result you want. To convert the key names, you'll want to use bracket notation, so something like: newObj[keyMap[oldKey]] = oldObj[oldKey] should work.
Here's a simple implementation for your example:
const obj = [{
SubmissionID: "28935",
MetaCreatedDate: "12 Mar 2018",
Program: "Brand Risk Management",
ViewedByInvestigator: "No",
}, {
SubmissionID: "28936",
MetaCreatedDate: "12 Mar 2018",
Program: "Brand Risk Management",
ViewedByInvestigator: "Yes",
}];
const nameMap = {
SubmissionID: 'SubmissionIdentifier',
MetaCreatedDate: 'CreationDate',
Program: 'ProgramName',
ViewedByInvestigator: 'Viewed'
}
function renameKeys(obj, map) {
const newObj = {};
for (let key in obj) {
newObj[map[key]] = obj[key];
}
return newObj;
}
console.log(obj.map(item => renameKeys(item, nameMap)));
I'd also note that if you happen to be using the lodash library, you can also use it's _.mapKeys method to do this.
I'm gonna use .map() function to change the key names. The input data will remain unchanged. Hope this helps.
var obj = [{
SubmissionID: "28935",
MetaCreatedDate: "12 Mar 2018",
Program: "Brand Risk Management",
ViewedByInvestigator: "No",
},
{
SubmissionID: "28936",
MetaCreatedDate: "12 Mar 2018",
Program: "Brand Risk Management",
ViewedByInvestigator: "Yes",
}]
var output = obj.map(element => ({
SubmissionIdentifier: element.SubmissionID,
CreationDate: element.MetaCreatedDate,
ProgramName: element.Program,
Viewed: element.ViewedByInvestigator
}));

JavaScript sort date followed by time in descending order [duplicate]

This question already has answers here:
How to sort an object array by date property?
(25 answers)
Closed 5 years ago.
I was having some problem to sort the date followed by time in descending order using JavaScript. Here is some inputs:
[{chatroomID: "1", date: "12/26/2017", time: "10:31:32 PM"},
{chatroomID: "2", date: "12/26/2017", time: "10:38:01 PM"},
{chatroomID: "3", date: "12/26/2017", time: "10:35:14 PM"}]
I wanted to sort them in descending order whereby the latest one will be on top but I not sure how to do it.
The desired output:
[{chatroomID: "2", date: "12/26/2017", time: "10:38:01 PM"},
{chatroomID: "3", date: "12/26/2017", time: "10:35:14 PM"},
{chatroomID: "1", date: "12/26/2017", time: "10:31:32 PM"}]
If the result comes from the same date, then I will sort according to time. Otherwise, the latest date will be on top. Any ideas?
Thanks!
Just concat the date and time, then parse it to a Date and get the timestamp. From then on, it's just plain old sorting.
const datetimes = [
{chatroomID: "1", date: "12/26/2017", time: "10:31:32 PM"},
{chatroomID: "2", date: "12/26/2017", time: "10:38:01 PM"},
{chatroomID: "3", date: "12/26/2017", time: "10:35:14 PM"}
]
const sorted = datetimes.sort((a, b) => {
const aDate = new Date(a.date + ' ' + a.time)
const bDate = new Date(b.date + ' ' + b.time)
return bDate.getTime() - aDate.getTime()
})
console.log(sorted)
Update: The linked answer in the comment by Marcel Gwerder indicates you could just skip getTime() altogether and just compare the Dates.

how to separate ng-repeat by date

I'm getting crazy to create a list separated by year and month name...
I would like to have something like:
Events in 2015
January
- event 1
- event 2
- event 3
February
- event 1
- event 2
...ecc...
Events in 2016
...ecc...
I don't think I have to create a repeater for each Year and Month, right? I think there is a filter or a rule to achieve this.
<div ng-app ng-controller="Main">
<div ng-repeat="event in events | what here?">
// how to create separators here?
{{event.title}}
</div>
</div>
$scope.events = [
{id: 1, title: "Title 1", date: 283764873126},
{id: 2, title: "Title 2", date: 283764873126},
{id: 3, title: "Title 3", date: 283764873126},
{id: 4, title: "Title 4", date: 283764873126}
];

Categories

Resources