Reputation: 113
I've read all of the related questions on here but nothing seems to work for me. I'm trying to take information from a .json file and sort it by nearest date to today and then present all the information relating to that event.
events.json
[
{
"title":"Event 1",
"start": "2014-12-06T09:00:00"
},{
"title":"Event 2",
"start": "2014-12-11T09:00:00"
},{
"title":"Event 3",
"start": "2014-12-13T10:00:00"
}
]
jQuery
$.getJSON( "events/events.json", function(data){
var array = $.map(data, function (item, index) {
console.log([item.title, item.start]);
});
});
Instead of, as I expected, showing me Array[3] (and then the events, start date) in the console, it shows me
["Event 1", "2014-12-06T09:00:00"]
["Event 2", "2014-12-11T09:00:00"]
["Event 3", "2014-12-13T10:00:00"]
Where am I going wrong?
EDIT: Thanks for all the help so far, but I think I've not been very clear with what I'm after. I want to get the data to display
Array[3]
{"Event 1", "2014-12-06T09:00:00"}
{"Event 2", "2014-12-11T09:00:00"}
{"Event 2", "2014-12-13T10:00:00"}
so that I can sort the array by date, if they are all in sub arrays, or their own arrays, I cant sort them against each other (or if I can, I don't know how, and didn't know you could!)
Upvotes: 0
Views: 109
Reputation: 363
If I understand well you simply want to display an array of 3 tuples instead of three arrays.
var parentArray = [];
$.getJSON( "events/events.json", function(data){
$.map(data, function (item, index) {
parentArray.push( { 'title': item.title, 'start': item.start } );
});
});
console.log(parentArray);
Your result will be:
[
{ 'title': 'Event 1', 'start': '2014-12-06T09:00:00' },
{ 'title': 'Event 2', 'start': '2014-12-11T09:00:00' },
{ 'title': 'Event 3', 'start': '2014-12-13T10:00:00' }
]
Upvotes: 1
Reputation: 4653
jQuery map function has two arguments. Index and item. Index comes first.
You want an array of arrays. Each inner array will have the two values.
So write
$.getJSON( "events/events.json", function(data){
var vals = [];
var array = $.map(data, function (index, item) {
vals.push([item.title, item.start]);
});
console.log(vals);
});
see here
Upvotes: 1
Reputation: 4274
use underscore sortBy and do something like
$.getJSON( "events/events.json", function(data){
var now = new Date();
var sortedArray = _.sortBy(data, function (item) {
return CALCULATEDIFFBETWEENDATES(now,item.start);
});
});
Upvotes: 0