Nida Amin
Nida Amin

Reputation: 755

Remove an element from array and save other duplicate entries

I have a global array with elements like this and which I have added to keep track of things and which contains duplicate values for counting the number of selection in the code.

arrayOfSelectedIds = [a1,a2,a1,a1,a1,a1]

I have a function:

function deleteSelection()
{
    var valueOfId  = "a1";
    arrayOfSelectedIds.remove(valueOfId);             
}

Now I want to remove it only one at a time i.e when the function is called the id value that is present in variable valueOfId should be removed only one time from array. I want the output should be like

arrayOfSelectedIds = [a2,a1,a1,a1,a1]

And if valueOfId = a2 then

arrayOfSelectedIds = [a1,a1,a1,a1,a1]

Please help !!!

Upvotes: 1

Views: 44

Answers (1)

Mamun
Mamun

Reputation: 68933

Array.prototype.splice()

The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

You can use splice() like the following way:

var arrayOfSelectedIds = ['a1','a2','a1','a1','a1','a1']

function deleteSelection(valueOfId){
  arrayOfSelectedIds.splice(arrayOfSelectedIds.indexOf(valueOfId), 1);             
}
deleteSelection('a1');
console.log(arrayOfSelectedIds);

Upvotes: 4

Related Questions