How to remove the specific value from Array Dynamically

HR Rajashekar
Mega Expert

Hi All,

I have requirement in scripting part where in

I created array and using "push" method to insert the value.

But I wanted to remove specific value from array and it will be selected dynamically.

Could any one help me out on this.

 

 

1 ACCEPTED SOLUTION

Matt Taylor - G
Giga Guru

You might try the splice function to drop a particular value from the array. Check the info about the splice function here.

 

// Given the following array:
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];

// Iterate through the array and test each value until we find the 
// one we're looking for and remove it
for( var i = 0; i < arr.length; i++){ 
   if ( arr[i] === 5) {
     arr.splice(i, 1); 
   }
}

//=> [1, 2, 3, 4, 6, 7, 8, 9, 0] This is the value of arr after the splice

View solution in original post

10 REPLIES 10

Matt Taylor - G
Giga Guru

You might try the splice function to drop a particular value from the array. Check the info about the splice function here.

 

// Given the following array:
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0];

// Iterate through the array and test each value until we find the 
// one we're looking for and remove it
for( var i = 0; i < arr.length; i++){ 
   if ( arr[i] === 5) {
     arr.splice(i, 1); 
   }
}

//=> [1, 2, 3, 4, 6, 7, 8, 9, 0] This is the value of arr after the splice

Hi Matt,

 

Thank you for your response.

 

As per the script , even If you add '5' again in the array , it will delete all the occurrence of '5'.

I mean to say I want to delete the selected value either first/last/own choice for only once.

You could add a break statement to the if block so that it will stop after the first time, or you can use the splice outside the if statement and for loop. The loop merely looks through the array for the particular value. You could add in some sort of counter that keeps track of the index positions of the value you're looking for. I guess I don't totally understand how you want this to work, but you can get creative with when you want the splice to take place and where in the array you want to use it.