Forum Discussion

ballard123's avatar
ballard123
Occasional Contributor
8 years ago

Groovy - Select position for related arrays and verify contents

Hello,   I have been looking for almost a week now around how to best approach this but cannot find anything.   I have two arrays which are related that are storing values from a loop through a J...
  • 05ten's avatar
    8 years ago

    I'd go with a matrix-approach. Define three lists in a list, one for index and two for your values. The just run find on the index-column and use the value to test the other two columns for what you are looking for. 

     

    def matrix = [[],[],[]];
    
    //Populate the matrix for this example
    3.times { i -> 
      matrix​[0][i] = i
      matrix[1][i] = "POST $i"
      matrix[2][i] = "TYPE $i"
    }
    //matrix
    //[[1,     2,      3],
    //[POST 0, POST 1, POST 2],
    //[TYPE 0, TYPE 1, TYPE 2]]
    
    //Search the indices and check the other two columns 
    //for their values using the current index
    int indexOfPost2Type2 = matrix[0].find { i -> 
       matrix[1][i] == 'POST 2' && matrix[2][i] == 'TYPE 2'
    }
    //indexOfPost2Type2 == 2

     

    try it out and see how that works. :)