Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array of objects of objects in javascript

I want to sort the below array by the "name" that is inside "user" object

 var myArr = [
 {"id":1,"user":{"name":"allen","id":101}},
 {"id":2,"user":{"name":"martin","id":102}}
]

how can I do this?

I have a method to sort array of objects but I can't use it for array of objects of objects

this is the method:

function dynamicSort(property) {
    var sortOrder = 1;
    if (property[0] === "-") {
        sortOrder = -1;
        property = property.substr(1);
    }
    return function (a, b) {
            var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
        return result * sortOrder;
    }
}

then I can sort using this:

myArr.sort(dynamicSort("id"));
like image 931
kouroshstst Avatar asked Jul 31 '18 14:07

kouroshstst


2 Answers

I would create property as a getter function (For the complex examples. You could check if propFn is a function, use this below for the more complex ones. See this answer for checking is propFn is a function.):

var myArr = [
  {"id":1,"user":{"name":"allen","id":101}},
  {"id":2,"user":{"name":"martin","id":102}}
]

function dynamicSort(propFn, sortOrder = 1) {
    return function (a, b) {
        var result = (propFn(a) < propFn(b)) ? -1 : (propFn(a) > propFn(b)) ? 1 : 0;
        return result * sortOrder;
    }
}

console.log(myArr.sort(dynamicSort((obj) => obj.user.name)));
console.log(myArr.sort(dynamicSort((obj) => obj.user.name, -1)));

Alternatively, you can take a look at: Convert JavaScript string in dot notation into an object reference

This will give you an idea of how you can convert period notation into a nested object, but I recommend reading the disclaimer at the top.

To maintain backwards compatibility, you could use something like this below:

var myArr = [
  {"id":1,"user":{"name":"allen","id":101}},
  {"id":2,"user":{"name":"martin","id":102}}
]

function dynamicSort(propFn, sortOrder = 1) {
    if (typeof propFn === "string") {
        let prop = propFn;
        if (prop[0] === "-") {
            sortOrder = -1;
            prop = prop.substr(1);
        }

        propFn = (obj) => obj[prop];
    }
    return function (a, b) {
        var result = (propFn(a) < propFn(b)) ? -1 : (propFn(a) > propFn(b)) ? 1 : 0;
        return result * sortOrder;
    }
}

console.log(myArr.sort(dynamicSort((obj) => obj.user.name)));
console.log(myArr.sort(dynamicSort((obj) => obj.user.name, -1)));
console.log(myArr.sort(dynamicSort("id")));
console.log(myArr.sort(dynamicSort("-id")));
like image 152
ugh StackExchange Avatar answered Oct 05 '22 20:10

ugh StackExchange


Edit:

If you are experiencing problems because of periods in your key names, this approach may be better suited as a solution. The path just has to either start as a bracket notation accessor or with a dot:

function dynamicSort(property, order) {
  order||(order=1);
  const getter = new Function("obj", "return obj" + property + ";");
  return function(a, b) {
    var result = (getter(a) < getter(b)) ? -1 : (getter(a) > getter(b)) ? 1 : 0;
    return result * order;
  }
}

var myArr = [{
    "id": 1,
    "user": {
      "name": "allen",
      "id": 101
    }
  },
  {
    "id": 2,
    "user": {
      "name": "martin",
      "id": 102
    }
  },
  {
    "id": 3,
    "user": {
      "name": "barry",
      "id": 103
    }
  }
]

console.log(JSON.stringify(myArr.sort(dynamicSort(".user.name"))));

Using the Object.byString() method from this answer, you can rewrite your function to take a path to the property you want to sort by:

var myArr = [
 {"id":1,"user":{"name":"allen","id":101}},
 {"id":2,"user":{"name":"martin","id":102}},
 {"id":3,"user":{"name":"barry","id":103}}
]

console.log(JSON.stringify(myArr.sort(dynamicSort("user.name"))));


function dynamicSort(property) {
    var sortOrder = 1;
    if (property[0] === "-") {
        sortOrder = -1;
        property = property.substr(1);
    }
    return function (a, b) {
            var result = (byString(a, property) < byString(b, property)) ? -1 : (byString(a, property) > byString(b, property)) ? 1 : 0;
        return result * sortOrder;
    }
}

function byString(o, s) {
    s = s.replace(/\[(\w+)\]/g, '.$1'); // convert indexes to properties
    s = s.replace(/^\./, '');           // strip a leading dot
    var a = s.split('.');
    for (var i = 0, n = a.length; i < n; ++i) {
        var k = a[i];
        if (k in o) {
            o = o[k];
        } else {
            return;
        }
    }
    return o;
}

I think it would be a little clearer and easier to use if you have the order as a second parameter, which means that your function should then more or less look like this:

function dynamicSort(property, order) {
  return function(a, b) {
    var result = (byString(a, property) < byString(b, property)) ? -1 : (byString(a, property) > byString(b, property)) ? 1 : 0;
    return result * order;
  }
}
like image 20
Luca Kiebel Avatar answered Oct 05 '22 18:10

Luca Kiebel