So your main problem is that you need to find the object in the internal array item with the corresponding property. Since you do not know what object it will be on. Please note that the limitation here is that you will always compare the first instance found, even if more than one object in item has a comparison property. Here:
var list = [ {"item":[{a:5, a1:6, a2:7}, {b:3, b1:4, b2:2}]}, {"item":[{a:1, a1:2, a2:3}, {b:4, b1:5, b2:6}]}, {"item":[{a:2, a1:7, a2:4}, {b:3, b1:7, b2:1}]} ]; function comparatorMaker(prop) { var findVal = function(acc, obj) { return acc || obj[prop]; }; return function(x, y) { if (!x.item && !y.item) return 0; if (x.item && !y.item) return -1; if (!x.item && y.item) return 1; var xVal = x.item.reduce(findVal, null) || 0; var yVal = y.item.reduce(findVal, null) || 0; return (xVal === yVal) ? 0 : (xVal > yVal) ? 1 : -1; }; } var myComparator = comparatorMaker('a'); list.sort(myComparator);
What happens here is that we generate a unique comparator function for the given property name. Now it will work with anyone:
var myComparator = comparatorMaker('b1'); list.sort(myComparator);
The findVal function that we define when executing the comparator function is used with item.reduce . The reduction is repeated over the contents of item and returns either the value already found or searches for the value for the current item under consideration. In fact, this can be done more efficiently, as we finish the iteration of each element in item , even if we immediately find a match, but in order to demonstrate this, it will take more lines of code.
The comparator itself should return 1, 0, or -1, depending on whether the resulting resulting values ββare more significant, equal, or less. The first few lines of the comparator function are designed to handle cases when the elements in list do not actually have the item property, because, as you formulated the question, it sounds as if it could be sometimes.