Remove items from the array that are also found in another array

I am currently working with two arrays structured as follows:

this.originalArray = [{
    id: 10,
    name: 'a',
    roleInfo: [{
        roleID: 5,
        roleName: 'USER'
    }]
},
{
    id: 20,
    name: 'b',
    roleInfo: [{
        roleID: 5,
        roleName: 'Admin',
    }]
 },
 {
     id: 30,
     name: 'c',
     roleInfo: [{
         roleID: 5,
         roleName: 'Support',
     }]
 }]

this.removeElements =      
    roleInfo: [{
        roleID: 5,
        roleName: 'Support',        
}]  

Query: How can the originalArray be filtered to exclude elements present in the removeElements array?

Answer №1

Here is how you can achieve this:

let filteredArray = originalArray.filter(item => removeElements.find(test => test.id == item.id));

Answer №2

Consider the following solution:

filteredArray = originalArray.filter(item => removeElements.some(f => f.id == item.id));

Answer №3

This method is compatible with most browsers.

var arrayOne = [1, 2, 3, 4, 5];
var arrayTwo = [2, 3];

var resultArray = [], foundValue;
for (var indexOne = 0; indexOne < arrayOne.length; indexOne++) {
    foundValue = false;
    // find arrayOne[indexOne] in arrayTwo
    for (var indexTwo = 0; indexTwo < arrayTwo.length; indexTwo++) {
        if (arrayOne[indexOne] == arrayTwo[indexTwo]) {
            foundValue = true;
            break;
        }
    }
    if (!foundValue) {
        resultArray.push(arrayOne[indexOne]);
    }
}

Alternatively, if compatibility is not a concern:

Use the following code snippet: a.filter(i => b.some(j => j.id === i.id));

Answer №4

let data = [
  { id: 10, name: 'a', roleInfo: [{ roleID: 5, roleName: 'USER' }] },
  { id: 20, name: 'b', roleInfo: [{ roleID: 5, roleName: 'Admin', }] },
  { id: 30, name: 'c', roleInfo: [{ roleID: 5, roleName: 'Support', }] }
]

let toRemove = [
    {
        id: 30,
        name: 'c',
        roleInfo: [{
            roleID: 5,
            roleName: 'Support',
        }]
    }
]

let finalArray = [];
data.forEach(function(item){
   let filterArray =  toRemove.filter(function(removeItem){
      if(removeItem.id == item.id && removeItem.name == item.name){
        return removeItem;
      }
    });
    if(filterArray.length === 0){
      finalArray.push(item);
    }
})

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

Validating the method for copying an array region in Dafny

I am currently undertaking a comparison of various programming languages that are designed with verification in mind, such as Whiley, Dafny, and Frama-C. I was provided with an example of a function that copies a region from one array to another array with ...

Issue with Angular 5 Application - "Implementations cannot be declared in ambient contexts"

Recently in my Angular 5 project, I started encountering an issue with the observable object. Everything was working smoothly until about a week ago when I began receiving this error message: ERROR in node_modules/rxjs/Observable.d.ts(20,31): error TS1183 ...

Detecting the presence of a session in Angular2 and nodejs using express

My server-side session creation is functioning properly, but I need to be able to hide certain elements in an Angular2 component template depending on whether the session exists. How can I check within my Angular2 component whether the server-created sessi ...

Sinon is unable to create a mock for a promise

This question has been asked frequently, and I have gone through all related queries on this topic. However, I am still having trouble applying the solutions to my specific case. The error I am encountering is as follows: Error: Timeout of 2000ms exceed ...

I'm seeking assistance with my PHP code: I'm struggling to access the elements in an array that is a property of an object

I am working with an object named 'aff' that has an array 'bill' as one of its properties. var_dump($aff); echo "<br/>"; print_r($aff->bill); echo "<br/>"; var_dump($aff->bill); echo "<br/>"; echo "<br/> ...

What is the best way to retrieve specific JSON data from an array in JavaScript using jQuery, especially when the property is

Forgive me if this question seems basic, I am new to learning javascript. I am currently working on a school project that involves using the holiday API. When querying with just the country and year, the JSON data I receive looks like the example below. ...

What is the best way to search through an array in TypeORM?

I am working on implementing user permissions management using TypeORM with PostgreSQL. The permissions are defined within the user entity in the following column: @Column({ type: 'text', array: true }) permissions: UserPermission[] = []; Th ...

Sharing precise API information between React components in React Components

I am currently learning react and facing an issue with sending data to other component files. I am trying to verify a user login from a backend API within an if statement, and if successful, I want to send the user ID to another component file. However, ...

In Internet Explorer, the loading time of an Angular 2 webpack application is being delayed by the presence of excessive ".js.map" files

https://i.stack.imgur.com/sY0tJ.pngEvery time I attempt to launch my Angular 2 webpack application on IE11, it noticeably takes longer to load compared to using Chrome. Upon inspecting the Network tab, I noticed that IE is attempting to fetch multiple fi ...

Exploring methods of testing a simple React functional component using Jest, TypeScript, and type annotations

I have been struggling for a long time to find a straightforward example of how to test a simple react component using jest and typescript. Despite my efforts, I have not been successful in finding a solution. I have checked out: https://basarat.gitbooks.i ...

Display an array using the MsgBox function in VBA

I'm not very experienced with VBA, but I'm looking to verify some values and could use some assistance. My goal is to create and display an array using the MsgBox function. The array is generated and populated within a for loop that performs cal ...

What is the mechanism by which the called function interprets the memory location of an array in call by reference?

Seeking a deeper understanding of passing an array by reference, I delved into an example from a book. Through experimentation in Code Blocks and some additional reading, a few key concepts became clear to me. First, when passing by value, the original v ...

The JSON object is being sent perfectly under the key "answer" instead of "array"

My android application is successfully receiving a positive response from our key:answer POST, but encountering issues with key:array for the same structure. Despite passing all JSON tests on the web, the web server seems to be rejecting the JSON data. The ...

Struggling to containerize an Angular application

Struggling to deploy my Angular application as a docker image on Azure, I have hit a roadblock. Following the steps outlined in a video tutorial at https://learn.microsoft.com/en-us/azure/developer/javascript/tutorial-vscode-docker-node-01?tabs=bash did no ...

Having trouble with the ngx-slick-carousel installation

I have been attempting to add the slick-carousel library to my Angular project by following the instructions outlined here: https://www.npmjs.com/package/ngx-slick-carousel. The first two steps, which are: npm install jquery --save npm install slick-caro ...

Creating a custom grid drag and drop feature within Angular Material adds a dynamic element to your application, going beyond basic list

According to the angular material documentation, creating a pure grid drag and drop feature is not straightforward. One solution I have come up with involves using multiple horizontal lists where items can only be dragged within their own row, resulting in ...

Updating the value of a radio button prior to triggering the click event

I am facing an issue with click events on my radio buttons. The validators are being set or cleared before the value actually changes. When the Yes radio button is clicked, I want to toggle the validators for the additional field that it reveals. If the N ...

What is the reason behind declaring an array of complex numbers row-wise in fftw?

The Manual for the Fastest Fourier Transform in the West, also known as FFTW, mentions on Page 4 that: The data is represented as an array of type fftw_complex, which is essentially a default double[2] array holding the real (in[i][0]) and imaginary (in ...

Neglecting to validate types in the personalized response format within Express

I'm new to typescript and I've run into a problem where I can't seem to get my types validated. Route app.use((req: Request, res: Response) => { // here 404 is a string but should be a number according to type defined but no error is s ...

Manipulating arrays of objects using JavaScript

I am working with an array of objects represented as follows. data: [ {col: ['amb', 1, 2],} , {col: ['bfg', 3, 4], },] My goal is to transform this data into an array of arrays like the one shown below. [ [{a: 'amb',b: [1], c ...