I am building a ticket management system for a state server we use at work. Back end is node.js with multiple front ends. I am rewriting my back end to be more maintainable as the scope grows.
For this particular function I start with this:
[
{
"id": 4993,
"ticket": "A142032570",
"sort": "07/22/14"
},
{
"id": 5060,
"ticket": "A142043078",
"sort": "07/23/14"
}
]
with many more entries than shown here. My function takes this data and creates this:
[
{
"date": "07/22/14",
"tickets": [
{
"id": 4993,
"ticket": "A142032570"
}
]
},
{
"date": "07/23/14",
"tickets": [
{
"id": 5060,
"ticket": "A142043078"
}
]
}
]
The function used is:
function sortMyTicketsByDate(data){
var arr = [];
for(var o in data){
arr.push(data[o].sort);
}
arr = _.uniq(arr);
for(var i in arr){
arr[i] = {date: arr[i]};
}
for(var d in arr){
console.log(arr[d]);
arr[d].tickets = [];
var elem = arr[d]['date'];
for(var o in data){
//data[o].sort, ticket, id
if (elem === data[o].sort) {
arr[d]['tickets'].push({id: data[o].id, ticket: data[o].ticket});
};
}
}
return arr;
}
What improvements can be made to sortMyTicketsByDate
to be more efficient/understandable?
arr
is an array, you're using the wrong loop, instead offor..in
you should use a regularfor
. \$\endgroup\$ – elclanrs Jul 31 '14 at 20:37for..in
is for looping objects, and object keys have no order; while an array is an object, if you want to loop it as an array, you need to use afor
loop, because it will keep the order, while the order offor..in
is not guaranteed by the spec. \$\endgroup\$ – elclanrs Jul 31 '14 at 20:42"07/22/14" < "07/21/15"
. Comparing strings are done via lexical comparisions \$\endgroup\$ – megawac Jul 31 '14 at 20:44