My JSON file looks like the following, somewhere around 1000-2000 objects.
[{
"date": "2015-01-25T22:13:18Z",
"some_object": {
"first_group": 20,
"second_group": 90,
"third_group": 39,
"fourth_group": 40
}
}, {
"date": "2015-01-25T12:20:32Z",
"some_object": {
"first_group": 10,
"second_group": 80,
"third_group": 21,
"fourth_group": 60
}
}, {
"date": "2015-02-26T10:53:03Z",
"some_object": {
"first_group": 12,
"second_group": 23,
"third_group": 13,
"fourth_group": 30
}
}]
After copying it in an array I need to perform the following manipulation on it:
First. Remove duplicate objects. 2 objects are considered the same if they have the same date
(without taking the time into consideration). So in my JSON, the first two objects are considered the same. Now the tricky part is that when a duplicate is found, we shouldn't just randomly remove one of them, but merge (not sure if merge is the right word) the fields from some_object
, so it becomes one object in the array. Therefore, with the JSON above, the first two objects would become one:
{
"date": "2015-02-26T00:00:00Z",
"some_object": {
"first_group": 30, //20+10
"second_group": 170, //90+80
"third_group": 60, //39+21
"fourth_group": 100 //40+60
}
}
Even trickier is that there could be some 3-10 objects with the same date, but different time in the array. Therefore those should be merged into 1 object according to the rule above.
Second. Sort this array of objects ascending (from oldest to newest of the date
field).
So what's so hard? Where did you get stuck?
I found out how to sort the array ascending (based on date
) by using this and some of this.
But I have no idea how to do the first point of removing the duplicates and merging, in a time-efficient manner. Maybe something inside:
var array = [];//reading it from the JSON file
var object_date_sort_asc = function (obj1, obj2) {
if (obj1.date > obj2.date) return 1;
if (obj1.date < obj2.date) return -1;
//some magic here
return 0;
};
array.sort(object_date_sort_asc);
Any ideas?