Utilize linqjs to filter an array based on the values present in another array

We have two arrays to work with here. The first array consists of objects:

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

The second array contains strings which are some ids:

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

The task at hand is to remove the objects from the first array that have ids present in the second array.

The expected result after deletion is as follows:

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

While exploring documentation on Linqjs, I came across the Except() method, which aids in eliminating elements from one array based on another.

To utilize this method effectively, a new array needs to be created from objectArray only containing elements whose ids match those in idsArray.

For example:

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

The creation of this new array can be achieved by using the Where() method provided by Linqjs.

The major challenge I face now is figuring out how to generate this new array while considering we have an array of ids for filtering purposes.

Answer №1

You have the option to utilize Vanilla JavaScript's array.filter and array.includes in the following manner:

let objectArray = [
  {FullName: "Person1", PersonId: "id1"},
  {FullName: "Person2", PersonId: "id2"},
  {FullName: "Person3", PersonId: "id3"},
  {FullName: "Person4", PersonId: "id4"}
];
    
  let excludeIdsArray= ["id1", "id2", "id3"];
  
  let newObj = objectArray.filter(obj => !excludeIdsArray.includes(obj.PersonId))
  
  console.log(newObj)

Alternatively, you can make use of array.reduce and array.includes like so:

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

let newObj = objectArray.reduce((arr, myObject) => {
  if(!excludeIdsArray.includes(myObject.PersonId)) {
    arr.push(myObject)
  } 
  return arr
}, [])
  

console.log(newObj)

Answer №2

To efficiently filter an array, you can utilize the filter() method. Create a set object using new Set() to easily check for the existence of the PersonId. This eliminates the need to iterate through each element with filter().

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

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

let idsToRemove = new Set(idsArray);
let result = objectArray.filter(o => !idsToRemove.has(o.PersonId));

console.log(result);

An alternative approach is to use includes() to determine if a specific string is present in an array.

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

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

let result = objectArray.filter(o => !idsArray.includes(o.PersonId));

console.log(result);

Note: To update the existing variable without creating a new one, you can directly reassign it like so:

objectArray = objectArray.filter(o => ...);

Answer №3

If you want to filter out specific items from an array based on certain criteria, you can leverage the Array.prototype.filter method along with indexOf. This allows you to check if a property like PersonId is present in an array of IDs that you want to exclude. If it's not found, you can then add it to a new array called filteredArray. Below is a code snippet demonstrating this:

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

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

// Use Array.prototype.filter method to eliminate unwanted elements
var filteredObjects = objects.filter(function(element) {
  return toDelete.indexOf(element.PersonId) === -1;
});

console.log(filteredObjects);

This approach utilizes pure JavaScript without relying on external libraries like linqjs. Consider removing unnecessary dependencies from your project for better maintenance.

Answer №4

To remove unwanted PersonId, one can utilize the Except function from linq.js. By providing an array of objects and a column parameter, excluding specific IDs becomes straightforward.

var objectArray = [{ FullName: "Person1", PersonId: "id1" }, { FullName: "Person2", PersonId: "id2" }, { FullName: "Person3", PersonId: "id3" }, { FullName: "Person4", PersonId: "id4" }],
idsArray = ["id1", "id2", "id3"],
result = Enumerable
.From(objectArray)
.Except(
Enumerable.From(idsArray).Select("{ PersonId: $ }"),
"$.PersonId"
)
.ToArray();

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered while using ReduxRouter within React.createElement

I am currently facing a challenge with implementing redux-router into my project. Despite my efforts, I have been unable to make it function properly. Here is a snippet of my routes definition: export default function(store) { return ( <Route pa ...

Retrieve the element by its id using JavaScript even when there are no form tags present on the webpage

Is it possible to retrieve an element by its ID using JavaScript when there is no form tag available? I am trying to obtain the value of a textbox with the following command, but I keep receiving a 'null or undefined' error message. It works cor ...

Issues Persist with Bootstrap Tree View - object passed but no output显示

After going through numerous discussions and solving several issues along the way, I have encountered a major problem where there is no output. As mentioned before, I am utilizing Bootstrap Tree View: To establish the hierarchical structure required for ...

Is there a way to change the labels of checkboxes within a table that is created dynamically?

I am new to JavaScript/jQuery and facing an issue with modifying checkbox labels in a dynamically generated table. <td> <input type="checkbox> <b>$18,000.00</b> ($18000+) Diamond Sponsor<br> <input type="checkbox> <b ...

Executing two nested loops with a delay in jQuery

I am currently working on a script that sends an ajax post to another page. I need to run two for loops before sending the ajax request with a timeout. The first loop is successful, but when I try to run the second loop, all requests are sent at the same ...

Form a triangle in order to prevent the inner content from spilling out

I'm currently attempting to design a triangle shape that prevents the inner content from overflowing while still allowing the inner content to be draggable. So far, I have experimented with various solutions such as polygons and canvas, but none of t ...

Prevent Cross-Array Data Usage in Angular Filter

I have two arrays - one with a complete list of data and another with only a few items. My goal is to filter out the data from the complete list that is not present in the second array and create a new array with the filtered results. Below are the detail ...

Guide on adding a button to a mat-table in Angular

I am looking to add a delete button or an Angular trash icon to a mat-table in an Angular application. Can anyone guide me on how to achieve this? Here is my current table code: <mat-table #table [dataSource]="ELEMENT_DATA"> <ng-container cdk ...

Chrome browser is experiencing an issue with the Modal RadWindow not closing properly

In my main "Report" page, there are actions available to the user that open a modal RadWindow. The user can then take actions within the modal window, click Save, and the modal window should close while the main grid refreshes. While this functionality wo ...

Focusing on the final (but not ultimate) elements within a specified tag

I am facing a challenge with an HTML structure containing multiple instances of a certain element along with two p elements beneath each: <some_tag></some_tag> <p></p> <p></p> <some_tag></some_tag> <p> ...

Examining the version of a node module installed in the local environment and comparing it

One of the reasons I am asking this question is because I have encountered challenges while collaborating with other developers. At times, when other developers update node module versions, I forget to install these new modules after pulling the latest co ...

What is the best method for binding variables in Vue.JS using moustache syntax and passing parameters to them?

If I have an HTML structure like this: <div> {{ CUSTOM_MESSAGE }} </div> And in my data: data() { return { CUSTOM_MESSAGE: 'Hey there! This message is for {{name}} from {{location}}' } } Is there a way to dynamically p ...

reach an agreement on the implementation of infinite scrolling when navigating backwards

I'm looking to create a feature where clicking the back button will return me to the same position on the page. A great example of this is on . If you scroll down, click on a product, and then go back from the product page, you'll be taken back t ...

AngularJS issue: Form submission does not trigger the controller function

I am currently learning AngularJS and I am experimenting with the sample code below to send my form data to the server. <!doctype html> <html lang=''> <head> <meta charset="utf-8"> <script src="../js/angular.min.v1 ...

What makes a pointer to pointer function like a matrix?

Could someone shed light on why a pointer to pointer is sometimes likened to a matrix in certain cases? Which specific property of C enables this comparison? Please refrain from responses like "A pointer to pointer is not always a matrix". I am aware of t ...

Add a fresh record only if it contains information and there are no existing duplicates present

Is it possible to create a note with both a title and text, under certain conditions? The title must not be empty The title cannot already exist in the system When attempting to check for duplicates within my array, the boolean value always returns true ...

Checking if a div element contains a child with a specific class name using JavaScript

Okay, so here's the dilemma: Is there a way to use JavaScript to determine if a DIV has a specific classname? For instance, consider this sample HTML <div class="cart"></div>. This DIV would act as the parent, and JavaScript would dynamic ...

Once the user clicks on the download button, the backend should initiate the download process

I am seeking a solution where a download can be triggered in the background when a download button is clicked, without interrupting other tasks. Is there a way to achieve this in PHP? If so, what method can be used? I have attempted using the curl function ...

Evaluating the Material ui Select element without relying on test identifiers

Currently, I am working with Material UI and react-testing-library to test a form. The form includes a Select component that is populated by an array of objects. import React, { useState } from 'react'; import { Select, MenuItem, FormControl, Inp ...

Unknown and void

undefined === null => false undefined == null => true I pondered the logic behind undefined == null and realized only one scenario: if(document.getElementById() == null) .... Are there any other reasons why (undefined === null) ...