Skip to main content

Hi all

 

I hope you can help me this one. I would like to write a function that can remove consecutive duplicate elements from a list. Furthermore certain rules should apply to which element to keep. The rules are:

 

  • The name attribute is key
  • If there is only one consecutive element choose that
  • If there are more consecutive elements (with the same key(name)) choose the first one where p=true. If there are no elements where p=true select the first element

 

Given this list:

 

[{name: "1", p: true}, {name: "2", p: false}, {name: "2", p: true}, {name: "3", p: true}, {name: "2", p: false}, {name: "2", p: false}]

 

the result should be:

 

[{name: "1", p: true}, {name: "2", p: true}, {name: "3", p: true}, {name: "2", p: false}]

 

I hope you can help :-)

 

/Uffe

13 respuestas
  1. 6 nov 2023, 13:15

    Hi @Uffe Rønne​ ,

     

    Check this script then:

    %dw 2.0

    output application/json

     

    fun checkPreviousBrother(item,index) = if(item.p == payload[index-1].p) null else (item)

     

    fun checkNextBrother(item,index) = do

    {

    var keepCurrent = ((item.p) default false)

    var keepNext= ((log(firstIteration[index+1]).p) default false)

    var nextItem = (firstIteration[index+1])

    ---

    if(keepCurrent)

    item

    else

    if(keepNext)

    nextItem

    else

    if(!keepCurrent and !keepNext)

    item

    else

    null

    }

    var firstIteration = payload map ((item, index) ->

    if(item.name == payload[index-1].name)

    checkPreviousBrother(item,index)

    else

    item )

     

    fun removeConsecutiveDuplicated(items) = items map ((item, index) ->

    if(item.name == payload[index-1].name)

    null

    else

    item)

    ---

    removeConsecutiveDuplicated(firstIteration map ((item, index) ->

    if(log(item).name == firstIteration[index+1].name)

    checkNextBrother(log(item),log(index))

    else

    item

    ) ) filter !isEmpty($)

    Hi @Uffe Rønne​ , Check this script then:%dw 2.0output application/json fun checkPreviousBrother(item,index) = if(item.p == payload[index-1]. 

    image 

    The tricky part of this script is that you need to divide the logic, and make like "phases". So, in each iteration of the array, you need to create intermediate variables to keep "looking" at the "new" result.

    In first iteration I checked the previous element from current, in second, the next one. Before ending, I've to remove "consecutives duplicates" and then remove the nulls I've been adding into the array.

     

    Hope it helps.

     

    Good luck!

    Juan Cruz Basso