rsturim
rsturim

Reputation: 6846

How do I sort a collection by their values?

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

Answers (2)

Tyron
Tyron

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.

  1. Create an array that contains only the Keys of your object.
  2. Sort that array by cross checking the values from your original object
  3. Access the values in a sorted order by iterating through your sorted keys array

Upvotes: 2

Guffa
Guffa

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

Related Questions