I have an array of objects in javascript, each of which in turn has an array:
{
category: [
{ name: "Cat1", elements : [
{ name: name, id: id } ]
},
{ name: "Cat2", elements : [
{ name: name, id: id },
{ name: name, id: id },
{ name: name, id: id } ]
},
{ name: "Cat3", elements : [
{ name: name, id: id },
{ name: name, id: id } ]
}
]
}
I would like to sort the array "category" based on the number of objects within the nested array "elements".
For example, after sorting, the above object might look like this (descending):
{
category: [
{ name: "Cat2", elements : [
{ name: name, id: id },
{ name: name, id: id },
{ name: name, id: id } ]
},
{ name: "Cat3", elements : [
{ name: name, id: id },
{ name: name, id: id } ]
},
{ name: "Cat1", elements : [
{ name: name, id: id } ]
}
]
}
I am wondering if it is possible to accomplish this using javascript's sort() method. Any suggestions?
Thanks in advance!
sort(byte[] a, int fromIndex, int toIndex) method sorts the specified range of the specified array of bytes into ascending numerical order. The range to be sorted extends from index fromIndex, inclusive, to index toIndex, exclusive.
The sort() method allows you to sort elements of an array in place. Besides returning the sorted array, the sort() method changes the positions of the elements in the original array. By default, the sort() method sorts the array elements in ascending order with the smallest value first and largest value last.
The sort
method accepts a function in which you can define how to compare two elements. Here's the relevant documentation.
compareFunction Specifies a function that defines the sort order. If omitted, the array is sorted lexicographically (in dictionary order) according to the string conversion of each element.
If compareFunction is supplied, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:
If compareFunction(a, b) is less than 0, sort a to a lower index than b.
If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
If compareFunction(a, b) is greater than 0, sort b to a lower index than a.
var sorted_categories = original.category.sort(function (one, other) {
//a - b is
// 0 when elements are the same
// >0 when a > b
// <0 when a < b
return one.elements.length - other.elements.length;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With