Search code examples
javascriptreactjstypescriptlodash

Filter a collection for everything except the values in an array (exclude the values in the array)


Trying out the lodash _.filter to return an array of values that excludes the values in an array. Say I have a collection of objects:

let col = {
    data: {
        name: "data1",
        type: "neighbor"
   },
},
{
    data: {
        name: "data2",
        type: "subordinate"
    }
},
{
    data: {
        name: "data3",
        type: "affiliate"
    }
}

let values = ["neighbor", "affiliate"];

I know I can do something like:

const elementsToKeep = _.filter(col, (v) => _.includes(values, v.data("type")));

which would return "neighbor" and "affiliate" but I want to return "subordinate" instead. I know this should be rather simple but I'm having a hard time figuring it out without writing more extensive logic.


Solution

  • Since the data is not structured properly as @BeerusDev mentioned, let me add the code as the answer and try to explain it.

    const col = [{
        data: {
          name: "data1",
          type: "neighbor"
        },
    
      },
      {
        data: {
          name: 'data2',
          type: 'subordinate'
        }
      },
      {
        data: {
          name: "data3",
          type: "affiliate"
        }
      }
    ];
    
    let values = ["neighbor", "affiliate"];
    
    const elementsToKeep = _.filter(col, (v) => !_.includes(values, v.data["type"]));
    
    console.log(elementsToKeep)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>

    Since the result of the _.includes is a boolean value, to get the data which is not inside the array that u have, we need to use !_.includes(...)