2

Is it possible at google-apps-script to sort an array of objects by a specified property?

5
  • why not? just google for how to sort an array of objects in javascript. I'm sure you'll get plenty of examples. Commented Jan 23, 2017 at 8:47
  • Can you give us an example, like what are you exactly looking for? What will be the contents of your array, from where are you populating it or is it static array? On what basis are you sorting it? Is it simple array of strings or numbers? Then you get direct function of sort(). Commented Jan 23, 2017 at 8:56
  • Thanks for the very quick answers! @ShyamKansagra: my object has just a view properties with strings and numbers... and now i want to sort an array with these objects by a specified propertie with a number in... that's it :) Commented Jan 23, 2017 at 9:12
  • @Fabian please give an example like this is my array: ['a','b','c'] and I want to sort it based on its alphabetical order or something like that. :) Commented Jan 23, 2017 at 9:18
  • @ShyamKansagra var arrayOne = [{name:"groupeOne", members:10},{name:"groupeTwo", members:20}]; now i want to sort by members... Commented Jan 23, 2017 at 9:23

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.