3

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 
[] 
Community
  • 1
  • 1
Avraam Mavridis
  • 7,742
  • 14
  • 68
  • 117
  • 2
    `$.grep` works fine for me: http://jsfiddle.net/J4cVY/. – Felix Kling Apr 28 '13 at 10:36
  • 1
    possible duplicate of [Remove specific element from a javascript array?](http://stackoverflow.com/questions/5767325/remove-specific-element-from-a-javascript-array) – Felix Kling Apr 28 '13 at 10:38

1 Answers1

6

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]
vishakvkt
  • 834
  • 6
  • 7
  • 3
    link to the documentation: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/splice – John Dvorak Apr 28 '13 at 10:40