javascriptarrayslinq.js

Filter one array using values from another array using linqjs


The first one is an array of objects:

let objectArray = [{
    FullName: "Person1",
    PersonId: "id1"
  },
  {
    FullName: "Person2",
    PersonId: "id2"
  },
  {
    FullName: "Person3",
    PersonId: "id3"
  },
  {
    FullName: "Person4",
    PersonId: "id4"
  }
];

The second one is an array of strings containing some ids.

let idsArray= ["id1", "id2", "id3"];

I need to delete the objects of the first array whose id are contained in the second array.

Expected result:

firstArray = [{
  FullName: "Person4",
  PersonId: "id4"
}];

Exploring Linqjs documentation I discovered that the Except() method allows me to remove elements from the first array using the second one as the "filter".

In order to use this method, I need to create a new array from objectArray that contains only the elements whose ids are contained on idsArray to use it as a parameter.

Example:

let filteredArray = Enumerable.From(objectArray).Except(theNewArray).ToArray();

To create this new array I can use the method Where() from Linqjs.

My problem starts here because I don't know how to create this new array considering that I have an array of ids to filter.


Solution

  • You can use Array.prototype.filter method in conjunction with indexOf to test if the PersonId property is found in the array of IDs to exclude - if it's not, add it to the new filteredArray. See below for example:

    let objects = [{
        FullName: "Person1",
        PersonId: "id1"
      },
      {
        FullName: "Person2",
        PersonId: "id2"
      },
      {
        FullName: "Person3",
        PersonId: "id3"
      },
      {
        FullName: "Person4",
        PersonId: "id4"
      }
    ];
    
    let toDelete = ["id1", "id2", "id3"];
    
    //just use Array.prototype.filter method to remove unwanted
    var filteredObjects = objects.filter(function(element) {
      return toDelete.indexOf(element.PersonId) === -1;
    });
    
    console.log(filteredObjects);

    This is achieved using vanilla JavaScript. I would advise you remove linqjs from your project's codebase if this is the only thing you're using it for.