Use of Filter function

Can someone explain the best use of filter function?

  Discussion posts and replies are publicly visible

Parents Reply Children
  • ,

    Can this function be used to calculate the local variable local!output in my below piece of code?

    a!localVariables(
    local!data:{{
    id:1,
    value:"test",
    order:"new",
    active:true
    ),
    {
    id:2,
    value:"qa",
    order:"old",
    active:false
    )}
    },


    local!output:index(local!data,
    wherecontains(1,tointeger(local!data.id))),


    local!output
    )

  • filter() is tricky (and in my opionion should be used only when necessary) since you need to call it either on a system function or on an expression rule if you need something more customized.  For your use case (assuming i'm reading your code correctly), you would probably be better off using a!forEach().

    For instance:

    a!forEach(
      local!data,
      
      if(
        fv!item.id = 1,
        fv!item,
        {}
      )
    )

  • Personally I almost never use the filter() function. I use its inverse reject() more often because it allows you to easily remove nulls from a list:

    a!localVariables(
      local!test: {1, null, 3, null, 7},
      reject(
        fn!isnull,
        local!test
      )
    )

    As far as implementing behavior for filtering, I often use a method very similar to what you mentioned. The where function lets you define a boolean for each item in the list, so it makes it easier to use in a variety of scenarios. For example, suppose I want to return all the items with a cost over 100:

    a!localVariables(
      local!data:{
        {
          id: 3,
          name: "Item 1",
          cost: 50
        },
        {
          id: 2,
          name: "Item 2",
          cost: 120
        },
        {
          id: 4,
          name: "Item 3",
          cost: 75
        },
        {
          id: 7,
          name: "Item 4",
          cost: 150
        },
      },
      index(
        local!data,
        where(
          tointeger(local!data.cost)>100
        ),
        {}
      )
    )

    If you want more complex logic, you can replace line 27 with whatever expression you want that returns a boolean and it should allow you to filter the data as needed.