Is it possible at google-apps-script to sort an array of objects by a specified property?
1 Answer
Based on the example that you have given in the comments, I have written a code to sort an array based on some particular property. I have used simple bubble sort on members values. ;) And it is sorting the array. It should work for you, not sure whether better options than this are available.
function myFunction() {
var arrayOne = [{name:"groupeOne", members:30},{name:"groupeTwo", members:20},{name:"groupThree",members:5}];
var n = arrayOne.length,swap;
for (var c = 0 ; c < ( n - 1 ); c++)
{
for (d = 0 ; d < n - c - 1; d++)
{
if (arrayOne[d].members > arrayOne[d+1].members)
{
swap = arrayOne[d];
arrayOne[d] = arrayOne[d+1];
arrayOne[d+1] = swap;
}
}
}
Logger.log(arrayOne);
}
1 Comment
Shyam Kansagra
I know there is in-built sort function available, but I don't know how we can pass a parameter such that it will sort based on it in these types of arrays with objects. If you know how to do it, please enlighten us.
sort().