sorting array in formula field?

Posted by gwf on 05-Jan-2015 09:46

Is it possible to sort an array in a formula field?

This code in a formula field results in an invalid return error:

var array = [5, 2, 1, 3, 4];

array.sort(
  function(a,b) {
    return a-b;
  }
);

return array[0];

Why won't this work?

Thank you,

Greg

Posted by Godfrey Sorita on 05-Jan-2015 11:51

Hi Greg,

Wrapping the process in a function should do the trick. Please see revised code below:

function main() {
  var array = [5, 2, 1, 3, 4];
  array.sort(function(a,b) {
    return a-b;
  });
  return array[0];
}

main();

Regards,

Godfrey

All Replies

Posted by Godfrey Sorita on 05-Jan-2015 11:51

Hi Greg,

Wrapping the process in a function should do the trick. Please see revised code below:

function main() {
  var array = [5, 2, 1, 3, 4];
  array.sort(function(a,b) {
    return a-b;
  });
  return array[0];
}

main();

Regards,

Godfrey

Posted by gwf on 05-Jan-2015 14:19

Thank you very much, Godfrey, that works.

For my future reference, could you please explain why this needs to be wrapped in a function?

Thanks,

Greg

Posted by Godfrey Sorita on 05-Jan-2015 15:05
In complex formulas, its body is automatically wrapped into a JavaScript function and that resultant function will represent the formula's result. If you are using custom-defined functions, your formula cannot be automatically wrapped and hence cannot include a return statement outside of a function.

For more information on formulas, please check this link: http://documentation.progress.com/output/Rollbase/#page/rb/formulas.html
Posted by gwf on 05-Jan-2015 16:28

Thank you very much!

Greg

This thread is closed