use cJobject to create a unique list

Here's something I do in many pieces of code on this site. Let's say that you have a list of things, lets say an array or a collection and you want to create a list of unique values. The .add() method of cJobject very handily only creates a child for new values. 
Private Sub cjList()
    ' use cjobject to get a unique list
    Dim a As Variant, cj As New cJobject, j As cJobject, i As Long
    a = Array("a", "b", "c", "c", "d", "d", "e", "a")

    With cj.init(Nothing)
        For i = LBound(a) To UBound(a)
            .add CStr(a(i))
        Next i
    End With
    
    For Each j In cj.children
        Debug.Print j.key
    Next j
End Sub

That means that the above code, very usefully produces a list of unique values in the given array - 
a,b,c,d,e

Organizing into families

Even, better, cJobject can organize things into families.
Private Sub cjListFamily()
    ' use cjobject to get a unique list
    Dim a As Variant, cj As New cJobject, j As cJobject, i As Long, jj As cJobject
    a = Array("smith.john", "smith.mary", "jones.fred", "jones.tom", "white.chalky", "smith.tom")

    With cj.init(Nothing)
        For i = LBound(a) To UBound(a)
            .add CStr(a(i))
        Next i
        Debug.Print .formatData
    End With

End Sub

gives us  
1.smith           
1.smith.john      
1.smith.mary      
1.smith.tom       
1.jones           
1.jones.fred      
1.jones.tom       
1.white           
1.white.chalky 

You want to learn Google Apps Script?

Learning Apps Script, (and transitioning from VBA) are covered comprehensively in my my book, Going Gas - from VBA to Apps script, available All formats are available now from O'Reilly,Amazon and all good bookshops. You can also read a preview on O'Reilly

If you prefer Video style learning I also have two courses available. also published by O'Reilly.
Google Apps Script for Developers and Google Apps Script for Beginners.



See How to use cJobject for more on this useful object.Take a look at One Liners for more tips like this. In the meantime why not join our forum,follow the blog or follow me on twitter to ensure you get updates when they are available. You can this example in the cDataSet.xlsm from Downloads 



Comments