How to sort array using Jquery

Viewed 225

I have one array, which includes children. I have successfully sorted the array but unable to sort it, children.

Using the below code I am able to sort outer mail array elements but not its children.

https://jsfiddle.net/eokd5uzj/

var arry = [{
    'id': 301,
    'name': '2 Foo',
    'open': 'open',
    'children': [{
        'id': 1313,
        'name': '2.1 Foo ',
        'open': 'open'
      },
      {
        'id': 1143,
        'name': '2.3 Foo ',
        'open': 'open'
      },
      {
        'id': 1132,
        'name': '2.2 Foo ',
        'open': 'open'
      },
    ],
  },
  {
    'id': 30,
    'name': '1 Foo',
    'open': 'open',
    'children': [{
        'id': 1134,
        'name': '1.1 Foo ',
        'open': 'open'
      },
      {
        'id': 1130,
        'name': '1.3 Foo ',
        'open': 'open'
      },
      {
        'id': 1123,
        'name': '1.2 Foo ',
        'open': 'open'
      },
    ],
  },
];


function SortByName(a, b) {
  var aName = a.name.toLowerCase();
  var bName = b.name.toLowerCase();
  return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
}


$(document).ready(function() {
  var sorted_array = arry.sort(SortByName)
  console.log(sorted_array)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id='data'>

</p>

4 Answers

You need to iterate the array as well for sorting all children. An assignment is not necessary, because Array#sort mutates the array.

array.forEach(({ children }) => children.sort(sortByName));

Please modify your function as below

function SortByName(a, b){
 if(a.children){
   a.children = a.children.sort(SortByName)
  }
  if(b.children){
   b.children = b.children.sort(SortByName)
  }
  var aName = a.name.toLowerCase();
  var bName = b.name.toLowerCase();
  return ((aName < bName) ? -1 : ((aName > bName) ? 1 : 0));
}

var updated_sorted_array = sorted_array.map(function(arr){
  arr.children = arr.children.sort(SortByName);
  return arr;
})

you need 2 functions to sort these objects, one for Desc and one for Asc sort like this:

function sortByKeyDesc(array, key) {
    return array.sort(function (a, b) {
        var x = a[key]; var y = b[key];
        return ((x > y) ? -1 : ((x < y) ? 1 : 0));
    });
}
function sortByKeyAsc(array, key) {
    return array.sort(function (a, b) {
        var x = a[key]; var y = b[key];
        return ((x < y) ? -1 : ((x > y) ? 1 : 0));
    });
}

And when you want to sort your objects you can pass in the original collection and the Column that you need to sort based on like this:

  function querySucceeded(data) {
     posts = [];
     posts = sortByKeyDesc(data, "TagName");
  }
Related