Reputation: 5733
I have e.g. an array like this:
var myArray = [];
var item1 = {
start: '08:00',
end: '09:30'
}
var item2 = {
start: '10:00',
end: '11:30'
}
var item3 = {
start: '12:00',
end: '14:30'
}
var item4 = {
start: '16:00',
end: '18:25'
}
var item5 = {
start: '19:00',
end: '21:25'
}
myArray.push(item1);
myArray.push(item2);
myArray.push(item3);
myArray.push(item4);
After sorting the order should look like this
[item1, item2, item5, item4, item3]
So the items with start- time before 12:00 should be ascending and the items with start time after or equal 12:00 sould be in reverse order.
I use AngularJS to iterate over the items:
<div ng-repeat="item in $scope.myArray" | orderBy:myOrderFunction? ...
and I would need the above order for ng-repeat. Is there a possibiliy to do this (in a performant way)?
Upvotes: 0
Views: 63
Reputation: 198324
That's quite weird, to be honest. However, this should do it:
function wiggleTime(time) {
var t = 60 * parseInt(time.substr(0, 2), 10) + parseInt(time.substr(3), 10);
return (t >= 720) ? 2160 - t : t;
}
function wiggleComparator(a, b) {
var aa = wiggleTime(a.start);
var bb = wiggleTime(b.start);
return aa - bb;
};
console.log(myArray.sort(wiggleComparator).map(function(o) { return o.start; }));
// ["08:00", "10:00", "19:00", "16:00", "12:00"]
To make it more performant, you could pre-wiggle the time and store it into the structure, so you wiggle it only once per element rather than twice per each tested pair.
Upvotes: 1
Reputation: 84
I have add a sort function in your code
myArray.sort(function(a, b) {
if(a.start.split(':')[0]>=12)
return a.start.split(':')[0] + b.start.split(':')[0];
else
return a.start.split(':')[0] - b.start.split(':')[0]
});
<div ng-app>
<div ng-controller="TodoCtrl">
<div ng-repeat="item in myArray" >
{{item.start}}
</div>
</div>
</div>
function TodoCtrl($scope) {
var myArray = [];
var item1 = {
start: '08:00',
end: '09:30'
}
var item2 = {
start: '10:00',
end: '11:30'
}
var item3 = {
start: '12:00',
end: '14:30'
}
var item4 = {
start: '16:00',
end: '18:25'
}
var item5 = {
start: '19:00',
end: '21:25'
}
myArray.push(item1);
myArray.push(item2);
myArray.push(item3);
myArray.push(item4);
myArray.push(item5);
myArray.sort(function(a, b) {
if(a.start.split(':')[0]>=12)
return a.start.split(':')[0] + b.start.split(':')[0];
else
return a.start.split(':')[0] - b.start.split(':')[0]
});
$scope.myArray=myArray;
}
Upvotes: 0