Skip to main content
November 17, 2021
Solved

Compare each item one by one in two arrays

  • November 17, 2021
  • 4 replies
  • 0 views

Hi

I need to compare each item in two arrays 

e.g.

local!dtmdata: {9, 9, 33, 33},
local!databaseData: {9, 33, 33, 33}

i have tried: 

a!localVariables(

local!dtmdata: {
9, 9, 33, 33
},
local!databaseData: {
9, 33, 33, 33
},
local!notAtIndex: a!forEach(
items: local!dtmdata,
expression: if(
wherecontains(fv!item,
local!databaseData

),
wherecontains(fv!item,
local!databaseData

),
"false"
)
),
local!notAtIndex
)

But its not sufficient as I want compare the numbers at each index

So I need to  compare the first item in array local!dtmdata with the first item in array local!databaseData and so on.  If at any point they are different then I need to know the index of the difference

in the example above it would return index 2 as it is different

Thanks!!

    Best answer by stefanhelzle0001

    a!localVariables(
      local!dtmdata: {9, 9, 33, 33},
      local!databaseData: {9, 33, 33, 33},
      where(local!dtmdata <> local!databaseData)
    )

    4 replies

    stefanhelzle0001
    Brainy
    November 17, 2021

    a!localVariables(
      local!dtmdata: {9, 9, 33, 33},
      local!databaseData: {9, 33, 33, 33},
      where(local!dtmdata <> local!databaseData)
    )

    nikolasAuthor
    November 18, 2021

    Wow, so simple. I was definitely overcomplicating it. Thank you!!!! 

    mikes0011
    Brainy
    November 17, 2021

    ...

    a!localVariables(
    
      local!dtmdata: { 9, 9, 33, 33 },
      local!databaseData: { 9, 33, 33, 33 },
      
      local!notAtIndex: a!forEach(
        items: local!dtmdata,
        expression: if(
          /* using index() here as it will allow the logic to run without breaking even if arrays are different lengths */
          index(local!databaseData, fv!index, null()) = fv!item,
          {},
          fv!index
        )
      ),
      
      local!notAtIndex
    )

    The Expression Guru
    csteward
    November 17, 2021

    Few ways to do this, but Stefan's solution is by far the most efficient.  However I might utilize a!foreach() with checking the max() length of either array to ensure all scenarios will be covered, and allow for scalability (say you want to ignore null values in the future).  If we can spare the extra ~1.5 ms:

    a!localVariables(
      local!dtmdata: {9, 9, 33, 33},
      local!databaseData: {9, 33, 33, 33},
    
      a!forEach(
        items: 1+enumerate(max(count(local!dtmdata),count(local!databaseData))),
        expression: if(
          index(local!dtmdata,fv!index,null)=index(local!databaseData,fv!index,null),
          {},
          fv!index
        )
      )
    )