How can I order datetime strings in Javascript? - javascript

I get from youtube JSON request (after a small parsing of the objects) these strings (which should represents datetime) :
2009-12-16T15:51:57.000Z
2010-11-04T10:01:15.000Z
2010-11-04T14:00:04.000Z
2010-11-04T11:12:36.000Z
2010-11-04T10:24:26.000Z
2010-11-04T12:05:58.000Z
2010-04-30T13:28:08.000Z
2010-11-17T13:57:27.000Z
In fact I need to order these list (descending), for taking the recent video published.
But how can I order those datetime? Is there a native method on JS?

You can just use a default sort method for this because the dates are perfectly formatted to do some sorting (year, month, day, hour, minute, second). This would be much more difficult if that was the other way around. Check out sort for example:
var unsortedArray = [
"2009-12-16T15:51:57.000Z",
"2010-11-04T10:01:15.000Z",
"2010-11-04T14:00:04.000Z",
"2010-11-04T11:12:36.000Z" ];
var sortedArray = unsortedArray.sort();
If you would like to reverse (descending) sorting, add .reverse() to the sorted array.

An easy way to achieve this would be to put all those into an array of strings and sort that array.
var arr = [ "2", "1", "3" ];
arr.sort(); // this gives [ "1", "2", "3" ]
You can read the full doc there :
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/sort

You asked for a descending sort. A quick way is to use reverse.
http://jsfiddle.net/6pLHP/
a = [
"2009-12-16T15:51:57.000Z",
"2010-11-04T10:01:15.000Z",
"2010-11-04T14:00:04.000Z",
"2010-11-04T11:12:36.000Z",
"2010-11-04T10:24:26.000Z",
"2010-11-04T12:05:58.000Z",
"2010-04-30T13:28:08.000Z",
"2010-11-17T13:57:27.000Z"
];
alert(JSON.stringify(a.sort().reverse()));

Related

Create Json with specific structure from two different arrays in javascript

I've already tried to find a solution on stack, but I didn't found a possible reply, so I decided to open a topic to ask:
Let's say we have 2 arrays: one containing "keys" and another one containing "values"
Example:
keys = [CO2, Blood, General, AnotherKey, ... ]
values = [[2,5,4,6],[4,5,6],[1,3,34.5,43.4],[... [
I have to create a Json with a specific structure like:
[{
name: 'CO2',
data: [2,5,4,6]
}, {
name: 'Blood',
data: [4,5,6]
}, {
name: 'General',
data: [1,3,34.5,43.4]
}, {
...
},
}]
I've tried to make some test bymyself, like concatenate strings and then encode it as json, but I don't think is the correct path to follow and a good implementation of it ... I've also take a look on JSON.PARSE, JSON.stringify, but I never arrived at good solution so... I am asking if someone know the correct way to implements it!
EDIT:
In reality, i didn't find a solution since "name" and "data" are no strings but object
Here's one way to get your desired output:
keys = ["CO2", "Blood", "General", "AnotherKey"]
values = [[2,5,4,6],[4,5,6],[1,3,34.5,43.4],[0] ]
const output = keys.map((x, i) => {
return {"name": x, "data": values[i]}
})
console.log(output)
However, since you're literally constructing key/value pairs, you should consider whether an object might be a better data format to output:
keys = ["CO2", "Blood", "General", "AnotherKey"]
values = [[2,5,4,6],[4,5,6],[1,3,34.5,43.4],[0] ]
const output = {}
for (let i=0; i<keys.length; i++) {
output[keys[i]] = values[i]
}
console.log(output)
With this data structure you can easily get the data for any keyword (e.g. output.CO2). With your array structure you would need to iterate over the array every time you wanted to find something in it.
(Note: The reason you weren't getting anywhere useful by searching for JSON methods is that nothing in your question has anything to do with JSON; you're just trying to transform some data from one format to another. JSON is a string representation of a data object.)

Converting a string to a list and seperate each element

So I have a use case in which I enter indexes and descriptions which belong to a round. I created a JS function that allows me to enter these indexes and descriptions. When I strip the data from the post request I get the following data:
['0,This is a testround', '1,This is a new testround']
I want to split this data so that I can seperate the 0 in an index variable and the following description "This is a testround" in a description variable. Please note that the description can only contain comma's. The indexes are not always corresponding with the indexes of an array: [[0,"Description1"],[5,"Description2"]] could happen
A possible solution could be to split the string on a comma and use str[0] for the index and the other parts for the description but to me this would look like an ugly solution.
What should I do?
I use the following JS to save the rounds to a playerdata div from which i extract the list above (in which items is the list with the index and description)
function item_checkbox(items,n) {
return `
<input type="checkbox" style="display:none;" name="${itemList[n]}" value="${items}" checked>
`
}
function add_to_itemData(items, n) {
itemDataEl = document.getElementById(itemData[n])
itemDataEl.innerHTML = itemDataEl.innerHTML + item_checkbox(items, n)
}
Thanks for any help in advance
While you say that it would be an "ugly" solution to solve it by splitting, I think it's a pretty straightforward routine, given the format the data is returned to you.
['0,This is a testround', '1,This is a new testround'].map(v => v.split(','));
... would translate correctly to:
[
[ "0", "This is a testround" ],
[ "1", "This is a new testround" ]
]
But I guess I get what you mean. There are a few possible problems - for example, that of key uniqueness. You could solve this one by keeping each row into Javascript objects instead of arrays, and you can convert it quite easily by using Object.fromEntries(), since it conveniently accepts each row of bidimensional arrays as key/value pairs:
Object.fromEntries([
[ "0", "This is a testround" ],
[ "1", "This is a new testround" ],
[ "1", "This is a dupe testround" ] // this will overwrite the previous entry
]);
// {0: "This is a testround", 1: "This is a dupe testround"}
You might want to take a few extra steps for additional control, like using .trim() to remove leading or trailing whitespaces or testing/filtering/splitting them using a custom regex.

HTML range slider show JSON dependant on date

I have a JSON file containing:
{"mapping": [
[
"london",
"51.18452",
"-0.150839",
"2016-04-19"
],
[
"london",
"52.6127",
"-2.02296",
"2016-04-21"
],
[
"london",
"53.334",
"-6.2761",
"2016-04-15"
]
}
Within my HTML I wish to have a range slider like this:
[]-----------------
oldest recent
In this scenario, the oldest JSON data should be shown, so
"london",
"53.334",
"-6.2761",
"2016-04-15"
And as the user slowly moves the range slider closer to the right end, more recent data should be shown..
----------------[]-
oldest recent
displaying..
"london",
"52.6127",
"-2.02296",
"2016-04-21"
I have many other values within the JSON file, I just used these three examples to show the format of the file. I am creating a heat map and whilst the slider moves along, the heat map should change to generate different points. Thanks for any help with this!
Turning the arrays into objects is optional, but it is much easier to reference properties like that, also it allowed us to convert the date string into a date object which has a number value to compare with.
const objectMapping = data.mapping.map(element => ({city:element[0], latitude:element[1], longitude:element[2], date:new Date(element[3])}));
Now that you have objects rather than an array, you can just say Array.sort on the date object where if b is higher than a, then b will come before a in the list
const sortedMapping = objectMapping.sort((a, b) => b.date - a.date);
Then sortedMapping[0] = oldest date

How to access an attribute from a JSON line saved in a position from an array?

This may be a very simple question but I really can't seem to make it work.
I have several JSON lines and a notes array.
Using notes.push(JSONline) I am saving one JSON line per array position, I assume, so in the following manner:
//notes[1]
{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":51}
//notes[2]
{"id":"27","valuee":"134","datee":"2016-04-05T15:15:47.238+0100","id2":53}
//notes[3]
{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":52}
Here is my problem: I want to print one specific attribute, for example id from one specific JSON line in the array. How can I do this?
When I do console.log(notes) it prints all the JSON lines just as expected. But if I do console.log(notes[1]) it prints the first character of the JSON line in that position, not the whole line.
Similarly console.log(notes[1].id) does not print the id from the first JSON line, in fact it prints 'undefined'.
What am I doing wrong?
Thank you so much.
I'd recommend that you parse all the json when you are pushing to notes, like:
notes.push(JSON.parse(JSONLine))
If you are somehow attached to having json strings in an array instead of objects, which I wouldn't recommend, you could always just parse once you have the jsonLine id
JSON.parse(notes[id]).id
Basically, you want to use JSON.parse for either solution and I'd strongly recommend converting them to objects once at the beginning.
You need to remember that JSON is the string representation of a JS object. JS strings have similar index accessor methods to arrays which is why you can write console.log(notes[0]) and get back the first letter.
JavaScript doesn't allow you to access the string using object notation, however, so console.log(notes[0].id) will not work and the reason you get undefined.
To access the data in the string using this method you need to parse the string to an object first.
var notes = ['{"id":"26","valuee":"20","datee":"2016-04-05T15:15:45.184+0100","id2":51}'];
var note0 = JSON.parse(notes[0]);
var id = note0.id;
DEMO
This leaves the question of why you have an array of JSON strings. While it's not weird or unusual, it might not be the most optimum solution. Instead you could build an array of objects and then stringify the whole data structure to keep it manageable.
var obj0 = {
"id": "26",
"valuee": "20",
"datee": "2016-04-05T15:15:45.184+0100",
id2: 51
};
var obj1 = {
"id": "27",
"valuee": "134",
"datee": "2016-04-05T15:15:47.238+0100",
"id2": 53
}
var arr = [obj0, obj1];
var json = JSON.stringify(arr);
OUTPUT
[
{
"id": "26",
"valuee": "20",
"datee": "2016-04-05T15:15:45.184+0100",
"id2": 51
},
{
"id": "27",
"valuee": "134",
"datee": "2016-04-05T15:15:47.238+0100",
"id2": 53
}
]
You can then parse the JSON back to an array and access it like before:
var notes = JSON.parse(json);
notes[0].id // 26
That's because you have {"id": "value"... as a string in your key value pairs. "id" is a string so you can't reference it like a property. 1. use
var notes = JSON.parse(notes);
as mentioned in the comments by The alpha
or remove the quotes try
{id:"26", ...}
that's why notes[i].id is returning undefined

Combining two Json feeds in one and sort them by time

How to combine two Json feeds in one and display them in one timeline by date using JS or jQuery?
For example we will have two Json responses (one from twitter and another from google+).
I need "n" numbers of latest items and show append them to show by items time.
Any ideas or hints?
Thank you!
Get the #number latest results from each feed:
var json1 = [{id:1, name: 'xxx' ...}]
var json2 = [{id:2, name: 'xyz' ...}]
var finalObj = json1.concat(json2);
Use the .sort JavaScript method for sorting by date.
You would need to create a custom compare function to check dates in both objects.
Check out this old question for more information on sorting by date:
Sort Javascript Object Array By Date
Show only the first #number elements of the sorted array.
var numberToShow = n - 1;
for (i = 0, x = numberToShow; i < x; i++) {
console.log(i);
}

Categories

Resources