Click here to Skip to main content
15,920,801 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
See more:
I have an array consisting of n elements. The number n is not known. How to delete those n elements from the array?
Posted
Updated 28-Nov-11 5:33am
v2
Comments
Sergey Alexandrovich Kryukov 28-Nov-11 11:33am    
Are you serious? Perhaps you just did not formulate it accurately, because it sounds to be too trivial -- please see my solution.
--SA

From your question, it looks like you need to delete all elements from the array. If so, assign your array variable to a new empty array. I am not sure that this trivial solution is what you really want. You need to be more accurate in questions.

If you want an ability to remove any random element, arrays are not good enough. Instead, you need to use Vector, List, LinkedList or ArrayList and use their remove methods.

Please see http://docs.oracle.com/javase/1.4.2/docs/api/java/util/Collection.html[^]; other collection types are listed on this page under "See Also"; please follow the links on each one to see what are they good for.

—SA
 
Share this answer
 
v3
Comments
Manoj K Bhoir 28-Nov-11 11:39am    
5 points
Sergey Alexandrovich Kryukov 28-Nov-11 11:45am    
Thank you, Manoj.
--SA
LanFanNinja 28-Nov-11 12:21pm    
My +5
Sergey Alexandrovich Kryukov 28-Nov-11 14:04pm    
Thank you.
--SA
Try this :

The splice() method adds and/or removes elements to/from an array, and returns the removed element(s).
Syntax:
JavaScript
array.splice(index,howmany,element1,.....,elementX)

index : Required. An integer that specifies at what position to add/remove elements
howmany : Required. The number of elements to be removed. If set to 0, no elements will be removed
element1, ..., elementX : Optional. The new element(s) to be added to the array

Example1 :
JavaScript
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write("Added: " + fruits.splice(2,0,"Lemon") + "<br />");
document.write(fruits);

Example2 :
JavaScript
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.write("Removed: " + fruits.splice(2,1,"Lemon") + "<br />");
document.write(fruits);

Output1 :
Added:
Banana,Orange,Lemon,Apple,Mango

Output2 :
Remove one element from position 2, and add a new element to position 2 in the array:
Removed: Apple
Banana,Orange,Lemon,Mango
 
Share this answer
 
v3
Comments
LanFanNinja 28-Nov-11 13:05pm    
+5
Are you looking at the n'th element? Then you can do as below
C#
ArrayList a = new ArrayList();
  a.Count
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900