Forum Discussion

jrhager84's avatar
jrhager84
Reel Rookie
2 years ago

My array is not sorting. How do I do it?

I have an array of associative arrays, and I want to sort the main array by the children array's 'displayOrder' property. I've looked at various solutions online, and none of them are doing what I want. I will give you an example:

{
  'displayOrder': 4,

  'title': 'Title Four'

  'videos': AssociativeArray<>...

},

{

  'displayOrder': 2,

  'title': 'Title Two',

  'videos': AssociativeArray<>...

}

 

I want to have the array be:

{

  'displayOrder': 2

  ...

},

{

  'displayOrder': 4

  ...

}

 

Basically, I'm getting arrays where the order is not right, and I need to 'sort' them, but the .sort() and sortBy() methods don't work the way I want, and no matter which type of sort algorithm or loop I do, it doesn't seem to do what I want to do (as would be in a traditional programming language). I'm sure it's something I'm doing, and I would appreciate some direction. Thanks!

2 Replies

  • renojim's avatar
    renojim
    Community Streaming Expert

    Is that really your code because it's full of syntax errors.  BS doesn't use single quotes for strings and you don't quote AA members.  It should be:

    x = [{displayOrder:4,title:"Title Four"}},{displayOrder:2,title:"Title Two"}]
    x.sortBy("displayOrder")

     

    P.S. - code is much easier to read if you use code tags.

    • jrhager84's avatar
      jrhager84
      Reel Rookie

      No - it's not. I figured it was obvious it was pseudo code. I just didn't see the code tag so it made it difficult to type. I'll be sure to use the tags in the future.

       

      It's correct and not throwing errors. I was able to diagnose that the fields *are* sorting if I print the array after the sort, but if some of the requests take a while it won't preserve order.