admin管理员组

文章数量:1325079

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 javascript or jquery 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 
[] 

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 javascript or jquery 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 
[] 
Share edited May 23, 2017 at 10:28 CommunityBot 11 silver badge asked Apr 28, 2013 at 10:33 Avraam MavridisAvraam Mavridis 8,94022 gold badges87 silver badges135 bronze badges 2
  • 2 $.grep works fine for me: jsfiddle/J4cVY. – Felix Kling Commented Apr 28, 2013 at 10:36
  • 1 possible duplicate of Remove specific element from a javascript array? – Felix Kling Commented Apr 28, 2013 at 10:38
Add a ment  | 

1 Answer 1

Reset to default 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]

本文标签: javascriptremove an element of an array and resize itStack Overflow