Refine the primary list by narrowing it down according to a secondary list

I created a filterList function to compare a mainList with a subList1. The function's goal is to identify the elements in the main list that are not present in subList1 and store them in subList2.

public filterList(mainlist: Selectitem[], subList1: Selectitem[]) {

let mainlistCopy = mainlist;
let subList2: SelectItem[] = [];

if (subList1) {

  mainlistCopy.forEach((element) => {
    if (element.title) {
      let itemExists = subList1.find((x) => x.id ==element.id);

      if (!itemExists) {
        subList2.push(element);
      }
    }

  });
}
return subList2;
}

Both lists are based on the following model:

interface IList {
id?: string;
// ...
}

When I run the function, I get an empty subList2 even though subList1 is a subset of mainList. Can anyone assist me in resolving this issue?

Answer №1

To accomplish this, you can utilize the filter method:

function filterList(mainList, subList1) {
  // Check for simple cases
  if(!subList1 
          || subList1.length === 0
          || !mainList
          || mainList.length === 0) {
    return mainList;
  }

  let subList2 = mainList.filter(elementMain => {
    // Compare elements and remove those present in subList1
    return !!elementMain.title && !subList1.find(element1 => element1.id === elementMain.id);
  });
  return subList2;
}

Answer №2

To enhance your current code, consider making the following adjustment:

let checkItem = subList1.find((x) => x.Id == element.Id);
if (checkItem === null) {
    subList2.push(element);
}

Another option is:

if (!subList1.some((x) => x.id == element.id)) {
    subList1.push(element);
}

Answer №3

Here is my approach to the problem:

if (!subList1 || subList1.length === 0) {
      return mainList;
    }

    let subList2: SelectItem[] = mainList.filter((element) => {
      return subList1.findIndex((item) => item.id == element.id) == -1;

    });

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

Tips for effectively utilizing the Angular ngIf directive for toggling the visibility of elements

<div *ngFor = "let element of myElements, let i=index" [ngClass]="{'selected':element[i] == i}"> <li> Name: {{element.element.name}}</li> <li> Description: {{element.element.description}}</li ...

If the item already exists within the array, I aim to replace the existing object with the new one

I am faced with a situation where I have an array of objects, and when a user selects an option, it adds a new object to the array. My goal is to write a code that can check if this new object's key already exists in one of the objects within the arra ...

Assigning variables within Redux saga generators/sagas

Consider this scenario: function* mySaga(){ const x = yield call(getX) } The value of const x is not determined directly by the return value of call(getX()). Instead, it depends on what is passed in mySaga.next(whatever) when it is invoked. One might a ...

Unused code splitting chunk in React production build would improve performance and efficiency of

When running the command npm run build, a build directory is generated with js chunks. I have observed an unfamiliar file named [number].[hash].chunk.js that does not appear in the list of entrypoints in the asset-manifest.json file. Instead, this mysteri ...

Is it possible for the app-routing.module.ts to have two paths with :/id?

When attempting to access the maindetail and childdetails pages using :/id, I encountered an issue on localhost where the desired card was not displaying on the maindetail page. The goal is to be able to click on the name "aniq" in the dashboard (image 1) ...

Next.js is perplexing me by throwing an error about Event handlers not being able to be passed to Client Component props, even though the component clearly has "use client" at

My bundler generates a basic React component like this "use client"; "use strict";var a=Object.create;var r=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var i=Object.getOwnPropertyNames;var l=Object.getPrototypeOf,s=Objec ...

Having trouble importing components from the module generated by Angular CLI library

After creating a simple Angular library using CLI with the command ng g library <library-name>, I encountered an issue while trying to import a component from its module. In my app module, I added components.module to the imports array and attempted ...

Accessing the currently operating WS server instance with NodeJS

After successfully setting up a basic REST API using NodeJS, ExpressJS, and routing-controllers, I also managed to configure a WebSocket server alongside the REST API by implementing WS. const app = express(); app.use(bodyParser.json({limit: "50mb"})); a ...

Establishing foreignObject coordinates in Angular

Struggling with setting the position (x, y) for foreignObject in Angular. I have attempted the following: <foreignObject width="65" height="50" x="{{position?.x}}" y="{{position?.y}}"> <div class="c ...

What are some ways to improve performance in JavaScript?

Can you help me determine which approach would be more efficient - using native functions of the language that involve 2 iterations or a simple for loop? The goal is to locate the index in an array of objects where the property filterId matches a specific ...

What is a Mongoose Schema type in TypeScript and how can it be used as a custom

https://i.stack.imgur.com/mtlRi.png Could anyone assist me with storing a custom object that includes attributes from the StationRating interface? ...

What is the best approach to manage the package versions of react, react-dom, @types/react, and @types/react-dom?

Recently, I decided to update the versions of react/react-dom in my project from 16.3.2 to 16.8.6 so that I could start using hooks. Surprisingly, after making some minor adjustments to my code, the update went smoothly. However, since we are utilizing ty ...

Can you please provide the origin of this Material 2 example document?

Click here to check out the extensive examples that delve deep into various ways of using Angular 2 Material 2 components. I'm struggling to locate the source of these examples in order to fully comprehend their implementation. Is there a specific p ...

WebSocket establishing fresh connection every passing moment

My Angular 5 application uses a socket.io-client to connect to a websocket server hosted on the Google Cloud Platform. However, instead of opening just one connection, I noticed that multiple connections are being created in the browser, with a new conne ...

"Exploring the world of jest.doMock: A guide to mocking

Here is the code snippet I am testing: ... import data from '../data/mock.json'; // function is async export const something = async () => { try { ... if (!data) { throw 'error is here!'; } ...

`Unable to upload spreadsheet file in xlsx format`

I'm currently working on implementing a feature to export data as xlsx files. I have been successful in exporting CSV and PDF formats, but encountered issues with the xlsx format due to dynamic imports. export const exportToXlsx = async ( gridElemen ...

Is it possible to navigate to a particular step during an Angular IntroJS event?

Whenever I attempt to navigate to a specific step from within the IntroJS onexit event, it seems to cause confusion and display the incorrect step along with the highlighted element. I have defined my steps using JSON, with a total of 8 steps: [{ elem ...

The latest version of IntelliJ Idea Ultimate, 2023.2.5, does not offer compatibility with the updated control flow features in Angular

I recently made the switch to Angular 17 in my project and noticed that Idea is not recognizing the new syntax in HTML templates. <mat-menu #menu="matMenu"> @for (menuItem of getData().menu.items; track menuItem) { & ...

Creating an array of objects data is a breeze with Vue.js

I have an array of data containing selected items, and I need to extract the IDs from this array into a new array so that I can send only the IDs to the back-end. Sample Code method toggleSelection(rows) { console.log('this.multipleSelection : &a ...

The value of 'this.selectedNodes' does not support iteration and is causing a

I am currently utilizing v-network-graphs to generate graphs in the front end with Vue. I have set up my data like this: data(){ return{ test: test_data, nodes:{}, edges:{}, nextNodeIndex: Number, selectedNodes: ref<st ...