Avraam Mavridis
Avraam Mavridis

Reputation: 8920

remove an element of an array and resize it

I want to remove an element of an array and resize the size of the array.
I used:

selectedproducts=jQuery.grep(selectedproducts, function(value) {
    return value != thisID;
});

but the size of selectedproducts remains the same.

I use:

console.log(selectedproducts.length);

To print the lenght of selectedproducts after every delete, but it doesn't change.

Is there a function in or to do that?

EDIT:

I had an Array with 5 elements.

What I get in the console using Felix's answer after every remove:

Size:4 
["Celery", "Tomatoes", undefined, "Carrots"]
Size:3
["Celery", undefined, "Carrots"] 
Size:2 
[undefined, "Carrots"] 
Size:1
[undefined] 

EDIT 2:

I tried vishakvkt's answer and works fine.

What I get in the console:

Size:4 
["Beans", "Avocado", "Snow Peas", "Tomatoes"] 
Size:3 
["Avocado", "Snow Peas", "Tomatoes"] 
Size:2 
["Avocado", "Snow Peas"] 
Size:1 
["Snow Peas"] 
Size:0 
[] 

Upvotes: 3

Views: 9284

Answers (1)

vishakvkt
vishakvkt

Reputation: 864

you should use Array.splice(position_you_want_to_remove, number_of_items_to_remove)

So if you have

   var a  = [1, 2, 3];
   a.splice(0, 1);  // remove one element, beginning at position 0 of the array
   console.log(a); // this will print [2,3]

Upvotes: 6

Related Questions