Ramesh Rajendran
Ramesh Rajendran

Reputation: 38683

Bulk delete in array by using typescript

I want to do bulk delete from an array using typescript.

I did it by using for loop.

this.versions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
this.selectedVersions = [1, 2, 3, 4, 5, 6];
for (let i = 0; i < this.selectedVersions.length; i++) {
  this.versions = this.removeObjectFromArray(this.versions, this.selectedVersions[i]);
}


//removing a object from array
removeObjectFromArray(listOfdata: any, data: any) {
  let index = listOfdata.findIndex(function (o) {
    return o === data;
  })
  listOfdata.splice(index, 1);
  return listOfdata;
}

But I don't like to use for loop.so let me know how to do bulk delete in array using typescript.

Upvotes: 0

Views: 997

Answers (7)

Grish Grigoryan
Grish Grigoryan

Reputation: 76

Typescript is the same as javascript, you can us all your knowledges from JS.

How do I remove a particular element from an array in JavaScript?

You can use for-of loop as well, if you TS compiler support

var versions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
var selectedVersions = [1, 2, 3, 4, 5, 6];
    for ( val of  selectedVersions)  {        
       if(selectedVersions.indexOf(val)!=-1){
           versions.splice(versions.indexOf(val), 1);
       }
    }

Upvotes: 0

Rahul Singh
Rahul Singh

Reputation: 19622

Make use of array.filter and filter the contents of the arrays based on the condition

let versions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
let selectedVersions = [1, 2, 3, 4, 5, 6];
versions = versions.filter(arrayVal => selectedVersions.indexOf(arrayVal) == -1 );
// checks for the values of selected Versions agains each value of versions and returns accordindly
console.log(versions)

Upvotes: 2

citizen conn
citizen conn

Reputation: 15390

I would personally use a filter for this to preserve the original arrays:

let nonSelectedVersions = this.versions.filter((e) => this.selectedVersions.indexOf(e) !== -1);

Upvotes: 1

BeetleJuice
BeetleJuice

Reputation: 40896

Use a filter

// will only keep elements that are not included in selectedVersions
this.versions = this.versions.filter(i => !this.selectedVersions.includes(i));

Upvotes: 2

Faly
Faly

Reputation: 13356

You can just use array filter:

var versions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
var selectedVersions = [1, 2, 3, 4, 5, 6];

versions = versions.filter(el => !selectedVersions.includes(el));
console.log(versions);

Upvotes: 5

&#193;lvaro Touz&#243;n
&#193;lvaro Touz&#243;n

Reputation: 1230

I think you can use indexOf, like this:

this.versions = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
this.selectedVersions = [1, 2, 3, 4, 5, 6];
  for (let i = 0; i < this.selectedVersions.length; i++)  
  {  
if(this.versions.indexOf(this.selectedVersions[i])!==-1){
this.versions.splice(index, 1);
}
  }

Upvotes: 1

Related Questions