Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort by object key in descending order on Javascript/underscore

I have the following object array where the key is the date in UTC format.

    Array = [{1436796000000:["Task1","Task2"],
         1437400800000:["Task4","Task8"],
         1436968800000: ["Task3","Task2"],
         1436882400000:["Task5","Task6"]}]

I want to sort this array object by key in descending order. So the expected output will be following like the latest date will come first.

    Array = [{1437400800000:["Task4","Task8"],
             1436968800000: ["Task3","Task2"],
             1436882400000:["Task5","Task6"],
             1436796000000:["Task1","Task2"]}]

How can I do this in javascript or using underscore.js?

like image 486
fyasir Avatar asked Jul 22 '15 03:07

fyasir


People also ask

How do you use descending order in JavaScript?

To sort an array of strings in descending order: Call the sort() method on the array. Call the reverse() method on the result. The returned array will have its elements sorted in descending order.

How do you sort elements in descending order?

To sort an array in Java in descending order, you have to use the reverseOrder() method from the Collections class.

Can you sort objects JavaScript?

Arrays of objects can be sorted by comparing the value of one of their properties.


1 Answers

No, that isn't an array, it's an object, and Javascript objects' properties are unordered by definition; so sorting them is meaningless.

You could instead use an array, which does have order, and restructure your data like this:

var arr = [
  { date: 1436796000000, value: ["Task1","Task2"] },
  { date: 1437400800000, value: ["Task4","Task8"] },
  { date: 1436968800000, value: ["Task3","Task2"] },
  { date: 1436882400000, value: ["Task5","Task6"] }
]

and then you can sort it by date:

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

If you don't want to restructure your data, you can iterate through it in the order you want, by getting an array of its keys and sorting that array, then using that array to access your object's properties, but you will need to do this each time your want to iterate through it in a particular order, since there is still no order information stored in the object:

// Get the array of keys
var keys = Object.keys( obj );

// Sort the keys in descending order
keys.sort( function ( a, b ) { return b - a; } );

// Iterate through the array of keys and access the corresponding object properties
for ( var i = 0; i < keys.length; i++ ) {
    console.log( keys[i], obj[ keys[i] ] );
}

You will need to shim Object.keys to support IE 8 and older browsers.

like image 189
Paul Avatar answered Sep 22 '22 05:09

Paul