Angular - Eliminate objects from an array based on their index matching a value in a separate array

I am facing a challenge with an array of indices and an array of objects:

let indices = [1,3,5]
let objArray = [{name: "John"}, {name: "Jack"}, {name: "Steve"}, {name: "Margot"},
                {name: "Tim"}, {name: "Elma"}]

My goal is to update objArray in a way that the entries matching the indices from the indices array are removed.

For example, the updated objArray should be:

[{name: "John"}, {name: "Steve"}, {name: "Tim"}]
as elements at positions 2, 4, and 6 matched the indices in the indices array.

I attempted to achieve this, however, the indexOf method is consistently returning -1.

for(let i=0;i<indices.length;i++) {
  if(objArray.indexOf(indices[i]) > -1) {
        delete objArray[indices[i]];
      }
}

Answer №1

Avoid removing elements from arrays directly; instead, utilize the powerful .filter method to exclude specific indices while iterating through the array:

let indices = [1,3,5]
let objArray = [{name: "John"}, {name: "Jack"}, {name: "Steve"}, {name: "Margot"},
                {name: "Tim"}, {name: "Elma"}]
const result = objArray.filter((_, i) => !indices.includes(i));
console.log(result);

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

InvalidAction: The function forEach cannot be applied to "res"

Here is the HTML code that I am currently working with: <div *ngIf="chart" class="col-xl-4 col-lg-6"> <div class="card cardColor mb-3"> <div class="card-header headColor"> <img class="img-fluid" src="../../../ ...

Looping through an array and adding its elements to a dictionary using JavaScript

I am struggling to figure out how to iterate over a dictionary with values in the form of arrays and then organize those values into a new dictionary. I am unsure of the steps needed to achieve this. Below is the data I need to iterate through: { t: [&quo ...

Encountered an issue in React Native/Typescript where the module 'react-native' does not export the member 'Pressable'.ts(2305)

I have been struggling to get rid of this persistent error message and I'm not sure where it originates from. Pressable is functioning correctly, but for some reason, there is something in my code that doesn't recognize that. How can I identify t ...

Jasmine was unsuccessful in detecting a exported function being invoked by another function

In my code, I've created 2 helper functions where one is a shortcut to the other. I need to verify in my test that the shortcut function is actually calling the main function. Both functions are located in the same file: export function test1(param1, ...

Is it best practice to encapsulate providers within an Angular module?

My list of service providers continues to grow: app.services.ts: providers: [ RegistrationService, LoginService, LoginPageGuard, LoggedInGuard, VerifiedGuard, LoggedInAndVerifiedGuard, UnverifiedGuard, NotLoggedInGuard ], When dealing with modules ...

How can I properly format an Angular locale date for API consumption?

I am currently utilizing two-way binding within my template-driven form: ts: searchLeaveApplication: any = {}; html: <mat-form-field class="searchInputs"> <input matInput [matDatepicker]="searchStartDate" [(ngModel)]="this.search ...

What are some solutions to the "t provider not found" error?

Upon deploying my application on the production server using GitLab/Docker, I encountered the following error message: ERROR Error: No provider for t! at C (vendor.32b03a44e7dc21762830.bundle.js:1) at k (vendor.32b03a44e7dc21762830.bundle.js:1) at t._thr ...

Guide on validating a dropdown using template-driven forms in Angular 7

Having trouble validating a dropdown select box, possibly due to a CSS issue. Any suggestions on how to fix this validation problem? Check out the demo here: https://stackblitz.com/edit/angular-7-template-driven-form-validation-qxecdm?file=app%2Fapp.compo ...

loop through an intricate JSON schema using Angular 5

I've been trying to figure out how to iterate a complex JSON in Angular 5. I came across the pipe concept, but it doesn't seem to work with JSON data like the one below. I'm trying to create an expandable table using this type of data, but I ...

Allowing Angular2 Components and their Sub Components to access a shared instance of ngModel within a service

Currently, I have been working on constructing a complex view that requires multiple functionalities. To ensure proper organization, I have divided it into various custom components. I don't want to go into great detail, but I have managed to make it ...

How can I modify the appearance of folders in FileSystemProvider?

I have created an extension for vscode that includes a virtual filesystem with fake directories and files. While the extension is functioning properly, I am facing some challenges in customizing certain aspects due to lack of documentation. 1) I need to u ...

Steps for performing a runtime cast

When working on a web application written in TypeScript, there is a feature where users can add additional JavaScript functions that will be parsed at runtime (new function(Function as String)) for execution. These functions should return an object defined ...

Please indicate the data type in Vue using Typescript

I'm currently struggling with Vue (3) + Typescript while attempting to specify a data property with a specific type. I have created a .d.ts file, but unfortunately, it hasn't helped. This is what I'm trying: import Modeler from 'bpmn-js ...

Oops! Looks like there was an issue finding a matching route for the URL segment in Angular 2

I am currently exploring angular2 and trying to figure out how to incorporate multiple <router-outlets> in a specific template. Despite searching through numerous Q&A, I have been unable to resolve the issue. router.module.ts const routes: Routes = ...

The current Angular 11 build seems to lack in producing sufficient Lazy chunk files

Currently, I am working on implementing lazy loading for modules from different libraries in my project. This involves utilizing two libraries located in the node_modules directory, which are then lazily loaded by the main application. Below is a snippet o ...

Switch button - reveal/conceal details

I am looking for assistance in toggling the visibility of information when clicking on an arrow icon. I have attempted to use JavaScript, but it was unsuccessful. My goal is to hide the information below by clicking on the downward-facing arrow image , an ...

Retrieve the outermost shell of the VUEjs wrapper test-utils

While working on a VueJS test, I encountered an issue where accessing the outermost layer of HTML seemed impossible. No matter what methods I tried, the outermost layer was always ignored. Is there a way to gain access to this outermost layer so that I c ...

Utilize NestJS to consume EventPattern exclusively when the header variable matches a specific value

I've been working on a NestJS project where I'm using a Kafka server to emit events and NestJS to consume them. My goal is to create a consumer with the topic my-topic that is triggered only when a specific value is present in the header variable ...

`Getting Started with TypeScript in an ASP.Net MVC Application`

Due to certain reasons, we have decided to begin our project with TS rather than JS. We are facing issues with the variables set in the MVC Views, which are established by the Model of each View. For example, tes.cshtml: @model Testmodel <script> ...

Creating a new formGroup and submitting it with model-driven form in Angular 2

Adding New Entries to FormArray Using input Field If I want to add values to an existing array through a form input, I can utilize the (click)="addAddress()" in the HTML file and define addAddress in the component.ts to update the values in an array withi ...