Forum Discussion

SuperTester's avatar
SuperTester
Contributor
4 years ago

Sorting an Array Object from FindAll

Hey guys!

 

I'm trying to figure out how to sort an array of objects by a certain property. However, I'm encountering an error where TC is saying "tableArray.sort is not a function".

Code:

const tableArray = window.FindAll("JavaClassName","UITablePeer$23",2000,true)

var sortedTableArray = tableArray.sort(function(a,b){return a.Left - b.Left})

 

Now, I know that TC supports the .sort() method because this example line of code does work:

const cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}
];

var sortedCarArray = cars.sort(function(a, b){return a.year - b.year});

 

My hunch is that there is a type difference between the tableArray and the cars array. In debugger, the cars array is a Array type whereas tableArray is a ComSafeArray. Could that be the reason for the discrepancy?

 

I tried declaring the resulting object from FindAll as a new array and it was just indexed into an array!

var tableArray = new Array(window.FindAllChildren("JavaClassName","UITablePeer$23",2000,true))

 

 

Thanks in advance!

 

 

  • Hey Marsha_R

    I think I just figured it out.

     

    By adding the .toArray command, the comSafeArray was converted to an array object and I can use the sort method.

     

    var tableArray = window.FindAllChildren("JavaClassName","UITablePeer$23",2000,true).toArray()

    var sortedTableArray = tableArray.sort(function(a,b){return a.Left - b.Left})

     

    Now, the documentation for the FindAll and FindAll children does warn that  JScript, C#Script and C++Script users need to convert using toArray(), but I did not think this applied to me since I'm coding in Javascript.

     

     

    • SuperTester's avatar
      SuperTester
      Contributor

      Hey Marsha_R

      I think I just figured it out.

       

      By adding the .toArray command, the comSafeArray was converted to an array object and I can use the sort method.

       

      var tableArray = window.FindAllChildren("JavaClassName","UITablePeer$23",2000,true).toArray()

      var sortedTableArray = tableArray.sort(function(a,b){return a.Left - b.Left})

       

      Now, the documentation for the FindAll and FindAll children does warn that  JScript, C#Script and C++Script users need to convert using toArray(), but I did not think this applied to me since I'm coding in Javascript.