0

I want to create a function that sorts an json object by two keys which I pass to function as arguments as shown below:

function sort_json_key1_then_key2(jsonObj, key_1, key_2) {

    jsonObj.sort(function(a, b) {
        if (a.key_1 == b.key_1) {
            return a.key_2 == b.key_2 ? 0 : +a.key_2 > +b.key_2 ? 1 : -1;
        }

        return +a.key_1 > +b.key_1 ? 1 : -1;
    });

}

Take the below json object as example:

var obj = [
            {"cl":"8","fare":"500.0","name":"41"},
            {"cl":"7","fare":"200.0","name":"37"},
            {"cl":"10","fare":"200.0","name":"33"},
            {"cl":"9","fare":"500.0","name":"29"},
            {"cl":"6","fare":"500.0","name":"29"}
        ];

I call the function to sort by 'fare' then 'cl' as follows:

var sorted = sort_json_key1_then_key2(obj, 'fare', 'cl');

var json_string = JSON.stringify(sorted);
console.log(json_string);

But I get 'undefined' as output in console. I think I am not correctly passing the keys as arguments to function correctly. Any idea on how to solve this?

Gp Master
  • 436
  • 1
  • 4
  • 15
  • Please read [What is the difference between JSON and Object Literal Notation?](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation) – str Apr 11 '18 at 13:53
  • Try `console.log(jsonObj)` – Jonas Wilms Apr 11 '18 at 13:55

1 Answers1

4

You have to use bracket notation instead of dot notation. Additionaly as you expect the function to return the result, you should actually return the sorted array. As .sort() mutates the original array, you might want to clone the array by spreading it into a new one ([...jsonObj]), so that the function is pure:

function sort_json_key1_then_key2(jsonObj, key_1, key_2) {
  return [...jsonObj].sort(function(a, b) {
    if (a[key_1] == b[key_1]) {
      return a[key_2] - b[key_2];
    }

    return a[key_1] - b[key_1];
  });
}

var jsonObj = [{
    "cl": "8",
    "fare": "500.0",
    "name": "41"
  },
  {
    "cl": "7",
    "fare": "200.0",
    "name": "37"
  },
  {
    "cl": "10",
    "fare": "200.0",
    "name": "33"
  },
  {
    "cl": "9",
    "fare": "500.0",
    "name": "29"
  },
  {
    "cl": "6",
    "fare": "500.0",
    "name": "29"
  }
];

var sorted = sort_json_key1_then_key2(jsonObj, 'fare', 'cl');

console.log(sorted);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
Eddie
  • 26,593
  • 6
  • 36
  • 58