user3318489 user3318489 - 1 month ago 8
AngularJS Question

AngularJS / javascript special sort order of javascript objects

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)?

Answer

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.

Comments