RomanGor
RomanGor

Reputation: 4475

Sort of internal content

How do I sort an object by the value of the child object?

Example:

[
    {
        name: 'Jhon',
        old: 20,
        last_message: {
            text: 'blah',
            timestamp: 1378188846
        }
    },
    {
        name: 'Bill',
        old: 45,
        last_message: {
            text: 'Hello, Jhon!',
            timestamp: 1378188956
        }
    },
    {
        name: 'Steave',
        old: 34,
        last_message: {
            text: 'Bye! ;)'
            timestamp: 1378188952
        }
    }
]

Should that be the order of objects independent of the maximum last_message.timestamp.

How to do it?

Upvotes: 1

Views: 50

Answers (2)

6502
6502

Reputation: 114569

You can specify a custom comparison function when sorting

my_list.sort(function(a, b){return ...});

you should return a negative number if a is less than b, a positive number if a is greater than b or 0 if they are equivalent.

By the way you really SHOULD pass a function because the default one will convert elements to strings and then compare the strings and this is rarely what you want except in the very case the array contains simply strings.

Not kidding if for example you've an array of numbers and call sort on it you will be surprised of the result as sorting

[1, 2, 3, 30, 20, 10]

gives by default

[1, 10, 2, 20, 3, 30]

because of that string conversion.

In your case a sorting function should be probably

function(a, b) {
    return a.last_message.timestamp - b.last_message.timestamp;
}

or the opposite, depending on if you want recent messages first or last

Upvotes: 2

Joon
Joon

Reputation: 9904

arr.sort(function(a, b) {
    return a.last_message.timestamp - b.last_message.timestamp;
});

Upvotes: 1

Related Questions