1

I have the follow json object

[
{"PARTNERNAME":"Partner 1","DISTANCE":20,"TYPE":"1"},
{"PARTNERNAME":"Partner 2","DISTANCE":14,"TYPE":"2"},
{"PARTNERNAME":"Partner 3","DISTANCE":60,"TYPE":"2"},
{"PARTNERNAME":"Partner 4","DISTANCE":37,"TYPE":"1"},
{"PARTNERNAME":"Partner 5","DISTANCE":25,"TYPE":"2"},
{"PARTNERNAME":"Partner 6","DISTANCE":90,"TYPE":"1"},
{"PARTNERNAME":"Partner 7","DISTANCE":49,"TYPE":"1"}
]

I'd like to sort it first by type and then by distance so the result would be the following.

[
{"PARTNERNAME":"Partner 1","DISTANCE":20,"TYPE":"1"},
{"PARTNERNAME":"Partner 4","DISTANCE":37,"TYPE":"1"},
{"PARTNERNAME":"Partner 7","DISTANCE":49,"TYPE":"1"},
{"PARTNERNAME":"Partner 6","DISTANCE":90,"TYPE":"1"},
{"PARTNERNAME":"Partner 2","DISTANCE":14,"TYPE":"2"},
{"PARTNERNAME":"Partner 5","DISTANCE":25,"TYPE":"2"},
{"PARTNERNAME":"Partner 3","DISTANCE":60,"TYPE":"2"}
]

I have the following code that sorts it by one field but I can get it to sort by two fields. Is this possible?

var sortedData = propertyArray.sort(sortByProperty('DISTANCE'));
function sortByProperty(property) {
            'use strict';
            return function (a, b) {
                var sortStatus = 0;
                if (a[property] < b[property]) {
                    sortStatus = -1;
                } else if (a[property] > b[property]) {
                    sortStatus = 1;
                }

                return sortStatus;
            };
        }
James Privett
  • 1,079
  • 3
  • 15
  • 23
  • 1
    A very good anser can be found here: http://stackoverflow.com/questions/2784230/javascript-how-do-you-sort-an-array-on-multiple-columns – Exinferis Jan 16 '15 at 12:13
  • JSON is text, that is an [*Array initialiser*](http://ecma-international.org/ecma-262/5.1/#sec-11.1.4), aka Array literal. – RobG Jan 16 '15 at 12:22

2 Answers2

1

Try this:

arr.sort(function(a, b){
    return a.TYPE === b.TYPE ? a.DISTANCE - b.DISTANCE : a.TYPE - b.TYPE
})
Mosho
  • 7,099
  • 3
  • 34
  • 51
  • It can actually be: `return a.TYPE - b.TYPE || a.DISTANCE - b.DISTANCE`l If the TYPE isn't equal it will sort on that and if it is equal, the first expression will be 0 and so the difference in distance is returned. – RobG Jan 16 '15 at 12:34
  • Excellent, works a treat. – James Privett Jan 16 '15 at 13:20
0

There is very useful function in LoDash:

console.log(_.sortBy(propertyArray, "TYPE", "DISTANCE"));

or custom solution:

function sortBy() { var arr = arguments[0]; var fields = [].slice.call(arguments, 1) return arr.sort(function (a, b) { for (var i = 0; i < fields.length; i++) { if (a[fields[i]] != b[fields[i]]) { return a[fields[i]] > b[fields[i]]; } } return 0; }); }

using:

console.log(sortBy(a, "TYPE", "DISTANCE"));

http://jsfiddle.net/hpzfLq76/

Rodion
  • 521
  • 2
  • 10