Reputation: 6846
I have a array of objects. I want to sort each object by their respective values using underscore.js.
var myArray = [
{a:1, b:2, c:2},
{a:1, b:3, c:2},
{a:3, b:2, c:1},
{a:1, b:1, c:4},
{a:1, b:2, c:4},
];
I've tried this method with no luck ...
var myArray = [
{a:1, b:2, c:2},
{a:1, c:2, b:3},
{c:1, b:2, a:3},
{a:1, b:1, c:4},
{a:1, b:2, c:4},
];
I'm trying using this method.
_.each(myArray, function(obj) {
_(obj).sortBy(function(val, key) {
return val;
});
});
here is my fiddle http://jsfiddle.net/rsturim/wNLkX/
Upvotes: 2
Views: 76
Reputation: 1976
As already mentioned, you can't sort properties in Javascript. What you can do however is to hold the sorting information in a separate array.
Upvotes: 2
Reputation: 700670
You can't sort properties in an object. The properties in an object doesn't have any specific order.
The order that the properties are returned when you loop through them is implementation dependant, and differs between browsers.
Upvotes: 5