user3711239
user3711239

Reputation: 41

Sort Array of objects with keys

I am trying all that I know in javascript. Is there a way to sort this based on key?

var myObj =[{"2":"installation.diagnostics.status"},{"4":"installation.diagnostics.status"},{"3":"installation.diagnostics.status"}];

Here is my code!!

var result=JSON.stringify(navMenu);

eval('var obj='+result);

console.log(obj);
Object.keys(obj)
      .sort()
      .forEach(function (k) {
         console.log(obj[k]);
      });

to

var myObj =[{"2":"installation.diagnostics.status"},{"3":"installation.diagnostics.status"},{"4":"installation.diagnostics.status"}]

Upvotes: 1

Views: 95

Answers (4)

cortexlock
cortexlock

Reputation: 1476

function sortArrayOfObjectsByKey(array, key, order){
    // can sort forward or in reverse - can be passed as integer or string
    // if order not passed in, defaults to 1 (forward)
    order = !order ? 1 : order;

    if (order === -1 || order.toString().toLowerCase() === "reverse"){
        array.sort(function(first, second) {
            if (first[key] < second[key]) { return 1; }
            else if (first[key] > second[key]) { return -1; }
            return 0;
        });
    }
    else {
        array.sort(function(first, second) {
            if (first[key] < second[key]) { return -1; }
            else if (first[key] > second[key]) { return 1; }
            return 0;
        });
    }
    return array;
}

Upvotes: 0

Andy
Andy

Reputation: 63589

You need to use a comparator function. This is the one to sort by strings which is what the object keys are.

function compare(a, b) {
  var ak = Object.keys(a)[0];
  var bk = Object.keys(b)[0];
  if (ak < bk) return -1;
  if (ak > bk) return 1;
  return 0;
}

myObj.sort(compare);

DEMO

Upvotes: 1

RobG
RobG

Reputation: 147503

Given:

var myObj =[{"2":"installation.diagnostics.status"},{"4":"installation.diagnostics.status"},{"3":"installation.diagnostics.status"}];

you can sort that using:

myObj.sort(function(a, b){return Object.keys(a)[0] - Object.keys(b)[0]});

You may need a polyfill for Object.keys to support older browsers.

Note that this sorts on the first returned property name as a number. If any member of myObj has more than one own property or the first returned isn't a digit, it may not work as expected.

Upvotes: 2

robieee
robieee

Reputation: 364

Try this :

 (function (s) {
    var t = {};
    Object.keys(s).sort().forEach(function (k) {
        t[k] = s[k]
    });
    return t
})(myObj)

It works for me.

Upvotes: 0

Related Questions