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/
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.