15

How to identify the index for the forEach loop in the Angular4 code.

I need to splice the record inside the foreach based on the condition.

angular.forEach(myObject => {
    if(!myObject.Name)
        myObject.splice(..., 1)
};

Here I want to delete the object if the name in myObject is blank.

2
  • Is myObject an array? Commented Oct 12, 2018 at 22:07
  • yes, it is an array. And I got the answer from HDJEMAI below. Commented Oct 15, 2018 at 20:39

2 Answers 2

36

forEach is documented here:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Syntax:

arr.forEach(callback(currentValue[, index[, array]]) { // execute something }[, thisArg]);

Parameters:

callback: Function to execute on each element. It accepts between one and three arguments:

currentValue: The current element being processed in the array.

index: Optional, The index of currentValue in the array.

array: Optional, The array forEach() was called upon.

thisArg: Optional, Value to use as this when executing callback.

To be able to use an index inside this forEach loop, you can add an index this way:

import { Component } from '@angular/core';

@Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
    name = 'Angular 6';
    myArray = [{name:"a"}, {name:""}, {name:"b"}, {name:"c"}];

    ngOnInit() {
        this.removeEmptyContent();
    }

    removeEmptyContent() {
        this.myArray.forEach((currentValue, index) => {
          if(!currentValue.name) {
              this.myArray.splice(index, 1);
          }
        });
    }
}

Working Stackblitz demo:

https://stackblitz.com/edit/hello-angular-6-g1m1dz?file=src/app/app.component.ts

Sign up to request clarification or add additional context in comments.

1 Comment

is angular.forEach the same as array.forEach?
0

Use the second parameter of the function for loop index.

angular.forEach(myArray,function(arrayItem,index){
  console.log(arrayItem,index);
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.