Skip to content

Commit f41cd5b

Browse files
fix(orderBy): ensure correct ordering with arrays of objects and no predicate
Closes angular#11866
1 parent 6a70e0e commit f41cd5b

File tree

2 files changed

+33
-9
lines changed

2 files changed

+33
-9
lines changed

src/ng/filter/orderBy.js

+10-3
Original file line numberDiff line numberDiff line change
@@ -190,11 +190,11 @@ function orderByFilter($parse) {
190190
if (reverseOrder) { array.reverse(); }
191191
return array;
192192

193-
function getComparisonObject(value) {
193+
function getComparisonObject(value, index) {
194194
return {
195195
value: value,
196196
predicateValues: predicates.map(function(predicate) {
197-
return getPredicateValue(predicate.get(value));
197+
return getPredicateValue(predicate.get(value), index);
198198
})
199199
};
200200
}
@@ -253,12 +253,19 @@ function orderByFilter($parse) {
253253
return '';
254254
}
255255

256-
function getPredicateValue(value) {
256+
function getPredicateValue(value, index) {
257257
var type = typeof value;
258258
if (type === 'string') {
259259
value = value.toLowerCase();
260260
} else if (type === 'object') {
261261
value = objectToString(value);
262+
263+
// If the object is a POJO then it doesn't really have a well defined ordering
264+
// To allow us to reverse the order of these objects, we artificially use its current
265+
// index in the collection as its value
266+
if (value === '[object Object]') {
267+
value = index;
268+
}
262269
}
263270
return { value: value, type: type };
264271
}

test/ng/filter/orderBySpec.js

+23-6
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,23 @@ describe('Filter: orderBy', function() {
143143
});
144144

145145

146+
it('should reverse array of objects with predicate of "-"', function() {
147+
var array = [
148+
{ id: 2 },
149+
{ id: 1 },
150+
{ id: 4 },
151+
{ id: 3 }
152+
];
153+
var reversedArray = [
154+
{ id: 3 },
155+
{ id: 4 },
156+
{ id: 1 },
157+
{ id: 2 }
158+
];
159+
expect(orderBy(array, '-')).toEqualData(reversedArray);
160+
});
161+
162+
146163
it('should not reverse array of objects with null prototype and no predicate', function() {
147164
var array = [2,1,4,3].map(function(id) {
148165
var obj = Object.create(null);
@@ -161,10 +178,10 @@ describe('Filter: orderBy', function() {
161178
null
162179
];
163180
expect(orderBy(array)).toEqualData([
164-
{ id: 2 },
165-
{ id: 3 },
166181
null,
167-
null
182+
null,
183+
{ id: 2 },
184+
{ id: 3 }
168185
]);
169186
});
170187
});
@@ -304,10 +321,10 @@ describe('Filter: orderBy', function() {
304321
null
305322
];
306323
expect(orderBy(array)).toEqualData([
307-
{ id: 2 },
308-
{ id: 3 },
309324
null,
310-
null
325+
null,
326+
{ id: 2 },
327+
{ id: 3 }
311328
]);
312329
});
313330
});

0 commit comments

Comments
 (0)