How can I use ternary in filter function?

I want to filter in the function. I tried, but it is not working correctly.

My task is if target_variable is true then only that true object will return, not all objects.

You can see activeColumns for example: not all target_variable are true, but right now all the object are getting displayed. Those target_variable value are false or if all target value is false then I have a second condition (that else case), but right now second case getting executed means this case : data.column_name !== ‘pk’ && data.data_type !== ‘TEXT’ getting executed.


  activeColumns: [
    {
      "column_name": "pk",
      "data_type": "BIGINT",
      "type": "continous",
      "target_timeseries": false,
      "target_variable": false,
      "final_format": "int"
    },
    {
      "column_name": "dewp",
      "data_type": "float",
      "type": "continous",
      "target_timeseries": false,
      "target_variable": true,
      "final_format": ""
    },
    {
      "column_name": "hmdy",
      "data_type": "float",
      "type": "continous",
      "target_timeseries": false,
      "target_variable": false,
      "final_format": ""
    },
    {
      "column_name": "mdct",
      "data_type": "TEXT",
      "type": "string",
      "target_timeseries": false,
      "target_variable": false,
      "user_format": "",
      "final_format": ""
    },
    {
      "column_name": "wdct",
      "data_type": "float",
      "type": "continous",
      "target_timeseries": false,
      "target_variable": false,
      "final_format": ""
    }
  ]
<Autocomplete
        options={
          activeColumns
            ? activeColumns
                .filter((data) =>
                  data.target_variable === true
                    ? data.target_variable === true
                    : data.column_name !== 'pk' && data.data_type !== 'TEXT'
                )
            : []
        }
/>

>Solution :

To filter only the objects that have a target_variable value of true, you can try:

<Autocomplete
  options={
    activeColumns
      ? activeColumns.filter(data => data.target_variable)
      : []
  }
/>

If all target_variable values are false, :

<Autocomplete
  options={
    activeColumns
      ? activeColumns.filter(data => data.target_variable)
                    .length > 0 
          ? activeColumns.filter(data => data.target_variable)
          : activeColumns.filter(data => data.column_name !== 'pk' && data.data_type !== 'TEXT' && data.column_name === 'dewp')
      : []
  }
/>

Leave a Reply