Sorting an Array of Objects by two Properties

typescript sort array of objects by multiple properties
sort multiple arrays javascript
javascript sort array of objects by key value
javascript sort multidimensional array multiple columns
lodash sort array of objects by multiple properties
array sort
lodash sort array of objects by property
sort array by a property

I've got an Array of Objects I want to sort by two Properties:

  1. RemindingTimestamp
  2. ModificationTimestamp

Sorting order: desc

Sorting this Object by one Property isn't the problem, but in this case I've no idea how to get it work.

Presuming the timestamps themselves sort ok (e.g. ISO8601 and same time zone), try:

myArray.sort(function(a,b) {
  var x = a.RemindingTimestamp - b.RemindingTimestamp;
  return x == 0? a.ModificationTimestamp - b.ModificationTimestamp : x;
}
Edit - response to comments

A descending sort is achieved by changing the order of subtraction, or multiplying the result by -1. Dates that don't sort because they don't subtract (e.g. 2012-04-12) can be handled by conversion to dates first, e.g.

// Convert ISO8601 date string to date object
// Assuming date is ISO8601 long format, ignores timezone
function toDate(s) {
  var bits = s.split(/[-T :]/);
  var d = new Date(bits[0], bits[1]-1, bits[2]);
  d.setHours(bits[3], bits[4], parseFloat(bits[5])); 
  return d;
}

// Source data, should end up sorted per n
var myArray = [ 
  {RemindingTimestamp: '2012-04-15T23:15:12Z', 
   ModificationTimestamp: '2012-04-15T23:15:12Z', n: 4},
  {RemindingTimestamp: '2012-04-12T23:15:12Z', 
   ModificationTimestamp: '2012-04-12T23:15:12Z', n: 1},
  {RemindingTimestamp: '2012-04-12T23:15:12Z', 
   ModificationTimestamp: '2012-04-13T23:15:12Z', n: 2},
  {RemindingTimestamp: '2012-04-12T23:15:12Z', 
   ModificationTimestamp: '2012-04-13T23:15:14Z', n: 3}
];

// Sort it
myArray.sort(function(a,b) {
  var x = toDate(a.RemindingTimestamp) - toDate(b.RemindingTimestamp);
  return x? x : toDate(a.ModificationTimestamp) - toDate(b.ModificationTimestamp);
});

// Just to show the result
function sa(o) {
  var result = [], t;
  for (var i=0; i<o.length; i++) {
    t = o[i]; 
      result.push(t.n);
  }
  alert(result);
}

sa(myArray); // 1,2,3,4

The conversion of date string to date object can be extended to handle time zone if required (for ISO8601 compliant strings only, those that use time zone abbreviations instead of the actual offset are unreliable).

Sorting an array by multiple criteria with vanilla JavaScript, Using Array.​​ sort() method let's you compare items in an array and sort them. To use it, you pass in a callback function that accepts two arguments. The first is the first item of the two it should compare, and the second is the second. You can name them anything you want. /** * Sorts an object into an order * * @require jQuery * * @param object Our JSON object to sort * @param type Only alphabetical at the moment * @param identifier The array or object key to sort by * @param order Ascending or Descending * * @returns Array */ function sortItems(object, type, identifier, order){ var returnedArray = []; var emptiesArray = []; // An array for all of our empty cans // Convert the given object to an array $.each(object, function(key, object){ // Store all of our

Sorting multiple object properties with JavaScript, Sorting regular arrays in javascript is a piece of cake - even sorting by object properties is simple. But sometimes you may want to provide the ability to sort by​  I like to sort an array with objects that have multiple properties. My objects have a string called name and a boolean called mandatory. First i want to sort on age, next on the name.

Custom comparators take the form:

myArray.sort(function(a,b){
  var m1=a1.RemindingTimestamp,
      m2=a2.RemindingTimestamp,
      n1=a1.ModificationTimestamp,
      n2=a2.ModificationTimestamp;
  return m1<m2 ? -1 : m1>m2 ? 1 :
         n1<n2 ? -1 : n1>n2 ? 1 : 0;
});

For descending sort, swap the < and > (or swap 1 and -1).

While you can make your own custom comparator each time you need this, I have created a method designed explicitly for easily sorting by multiple criteria, using a Schwartzian transform (which may be faster but more memory hungry in some circumstances): http://phrogz.net/js/Array.prototype.sortBy.js

In short:

myArray.sortBy(function(obj){
  return [obj.RemindingTimestamp, obj.ModificationTimestamp];
}).reverse();

The reverse is there since you mentioned that you wanted a descending sort. If both RemindingTimestamp and ModificationTimestamp are numbers, you could alternatively do:

myArray.sortBy(function(obj){
  return [-obj.RemindingTimestamp, -obj.ModificationTimestamp];
});

Here is the code that adds sortBy to arrays:

(function(){
  // Extend Arrays in a safe, non-enumerable way
  if (typeof Object.defineProperty === 'function'){
    // Guard against IE8's broken defineProperty
    try{Object.defineProperty(Array.prototype,'sortBy',{value:sb}); }catch(e){}
  }
  // Fall back to an enumerable implementation
  if (!Array.prototype.sortBy) Array.prototype.sortBy = sb;

  function sb(f){
    for (var i=this.length;i;){
      var o = this[--i];
      this[i] = [].concat(f.call(o,o,i),o);
    }
    this.sort(function(a,b){
      for (var i=0,len=a.length;i<len;++i){
        if (a[i]!=b[i]) return a[i]<b[i]?-1:1;
      }
      return 0;
    });
    for (var i=this.length;i;){
      this[--i]=this[i][this[i].length-1];
    }
    return this;
  }
})();

Here are some more examples from the docs:

var a=[ {c:"GK",age:37}, {c:"ZK",age:13}, {c:"TK",age:14}, {c:"AK",age:13} ];

a.sortBy( function(){ return this.age } );                                  
  --> [ {c:"ZK",age:13}, {c:"AK",age:13}, {c:"TK",age:14}, {c:"GK",age:37} ]

a.sortBy( function(){ return [this.age,this.c] } );                         
  --> [ {c:"AK",age:13}, {c:"ZK",age:13}, {c:"TK",age:14}, {c:"GK",age:37} ]

a.sortBy( function(){ return -this.age } );                                 
  --> [ {c:"GK",age:37}, {c:"TK",age:14}, {c:"ZK",age:13}, {c:"AK",age:13} ]


var n=[ 1, 99, 15, "2", "100", 3, 34, "foo", "bar" ];

n.sort();
  --> [ 1, "100", 15, "2", 3, 34, 99, "bar", "foo" ]

n.sortBy( function(){ return this*1 } );
  --> [ "foo", "bar", 1, "2", 3, 15, 34, 99, "100" ]

n.sortBy( function(o){ return [typeof o,this] } );
  --> [1, 3, 15, 34, 99, "100", "2", "bar", "foo"]

n.sortBy(function(o){ return [typeof o, typeof o=="string" ? o.length : o] })
  --> [1, 3, 15, 34, 99, "2", "100", "bar", "foo"]

Note in the last example that (typeof this) happens not to be the same as (typeof o); see this post for more details.

JavaScript Sort by Two Fields (Example), A protip by davidcollingwood about multiple, javascript, and sort. So the problem was that I had an array like this: var obj = [ { "one": 1, "two": 9 }  Let’s create a sorting function, which you can use to sort an array of objects, whose values are either strings or numbers. This function has two parameters — the key we want to sort by and the

Assuming that both properties are in the same sortable format, here's another way of deep sorting in ES6:

const comparingFunction = (a, b) => {
  if (a.property1 < b.property1) {
    return -1;
  }
  if (a.property1 > b.property1) {
    return 1;
  }

  if (a.property1 == b.property1) {
    if (a.property2 < b.property2) {
      return -1;
    }
    if (a.property2 > b.property2) {
      return 1;
    }
    return 0;
  }
};

myArrayOfObjects.sort(comparingFunction);

Hope it helps somebody.

JavaScript Array sort() Method, How do you sort an array of objects by multiple fields? This will sort your array by "one" and if they are the same (ie. 0) then it will sort by "two". It's simple, concise, readable, and best of all - works perfectly.

Another way

function sortBy(ar) {
  return ar.sort((a, b) => a.RemindingTimestamp  === b.RemindingTimestamp  ?
      a.ModificationTimestamp.toString().localeCompare(b.ModificationTimestamp) :
      a.RemindingTimestamp.toString().localeCompare(b.RemindingTimestamp));
}

javaScript: sorting an array with multiple object/properties , by votes // If the first item has a higher number, move it down // If the first item has a lower number, move it up if (vote1. votes > vote2. votes) return 1; if (vote1. votes < vote2. But if, for some reason, you wanted to keep using List.Sort(), it means you have write a custom IComparer or Comparison. And you can use the ComparerExtensions library to write the comparer using a more readable, LINQ-like syntax: things.Sort(KeyComparer<Thing>.OrderBy(thing => thing.Width).ThenBy(thing => thing.Length));

How to sort an array of object by two fields in JavaScript , () method sorts the values as strings in alphabetical and ascending order. You want to render this list, but first you want to order it by the value of one of the properties. For example you want to order it by the color name, in alphabetical order: black, red, white. You can use the sort() method of Array, which takes a callback function, which takes as parameters 2 objects contained in the array (which we call a and b):

How to sort an array of objects by a property value in JavaScript, Hello every one, I am trying to build a card game using javaScript. I have used the .sort() method to reorder my deck of cards. My array is  If you had an array of objects with more than two properties, you could, for example, sort by a third criteria if the titleproperty was the same between two items (maybe locationor year).

Sorting an array of objects, There are two methods to solve this problem which are discussed below: Approach 1: First compare the first property, if both are unequal then sort accordingly. The employees array above is an array of objects with properties of different data types, from string, numeric, to a date string. The sort() method can be used to sort the array based on the values of one of these properties, such as sorting the array by name, age, or even when they retire. The basic idea is to modify the compare function so it compares the desired properties' values.

Comments
  • Compare the first property. If the property value is the same for two elements, only then compare the second property. (Haven't you ever sorted a deck of playing cards?)
  • What are the types of these properties? Numbers, strings, or dates?
  • Note that the OP mentioned a descending sort.
  • Note also that if these are ISO8601 strings, subtracting them isn't going to work.
  • @Phrogz—a descending sort is achiived by changing a - b to b - a. ISO8601 short dates sort (e.g. 20120412), long dates can be converted to date objects before subtraction.
  • I love this solution, wish I could do more than +1 :)