473,714 Members | 2,500 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Removing an element of an array

I wrote a simple script to remove an element of an array but I don't
think this is the best way to go about it.

I have a list of about five elements seperated by ";"

I split the array using array.split(";" ) command and proceeded to
update the elemment by assigning the null value to the arrayindex

array[index]=""

This of course assigns null to the element

But there are two problems

1. The array size is still five instead of 4
and my list is now seperated by "," with an exta "," to go.

Can anyone suggest a more effective way of doing this?

Thank you.

Jul 23 '05 #1
5 6381
ef*****@epitome .com.sg wrote:

[snip]
array[index]=""

This of course assigns null to the element


It does not. It assigns an empty string to the element. This neither
the same thing, nor does it delete the array element.

To actually delete an array element, you must shift all elements above
the deletion point to overwrite the to-be-deleted elements and then
truncate the array. The splice method does this:

Array.prototype .splice(index, count, item1, item2, ...);

index - The position in the array where deletion/insertion begins.
count - The number of elements to delete.
item1 - An optional argument which specifies a value to insert once
count elements have been deleted.

For example, consider the following actions with array [1, 2, 3, 4]:

result = array.splice(2, 1);

array: [1, 2, 4]
result: [3]
result = array.splice(0, 2);

array: [3, 4]
result: [1, 2]
result = array.splice(3, 1, 5, 6, 7);

array: [1, 2, 3, 5, 6, 7]
result: [4]
result = array.splice(0, 4, 5);

array: [5]
result: [1, 2, 3, 4]

From the penultimate examples, you can see that the splice method can
expand an array if the number of inserted elements outnumbers the
number of deleted elements.

The only problem with the splice method is that IE provided a late
implementation of it, meaning versions earlier than IE5.5 will not
have the method (unless a newer JScript version has been installed).

A complete implementation of splice is included below which can
supplement an older browser:

if('function' != typeof Array.prototype .splice) {
Array.prototype .splice = function(s, dC) {s = +s || 0;
var a = [],
n = this.length,
nI = Math.min(argume nts.length - 2, 0),
i, j;
s = (0 > s) ? Math.max(s + n, 0) : Math.min(s, n);
dC = Math.min(Math.m ax(+dC || 0, 0), n - s);
for(i = 0; i < dC; ++i) {a[i] = this[s + i];}
if(nI < dC) {
for(i = s, j = n - dC; i < j; ++i) {
this[i + nI] = this[i + dC];
}
} else if(nI > dC) {
for(i = n - 1, j = s + dC; i >= j; --i) {
this[i + nI - dC] = this[i];
}
}
for(i = s, j = 2; j < nI; ++i, ++j) {this[i] = arguments[j];}
this.length = n - dC + nI;
return a;
};
}

You can just include the code above: if a browser doesn't implement
splice, this code will automatically be used. If a browser does
implement splice, the existing code will be used instead.

If you're only interested in deleting elements from an array, the code
above can be simplified slightly (but maintaining the same semantics) to:

if('function' != typeof Array.prototype .splice) {
Array.prototype .splice = function(s, dC) {s = +s || 0;
var a = [],
n = this.length,
i, j;
s = (0 > s) ? Math.max(s + n, 0) : Math.min(s, n);
dC = Math.min(Math.m ax(+dC || 0, 0), n - s);
for(i = 0; i < dC; ++i) {
a[i] = this[s + i];
this[s + i] = this[s + i + dC];
}
this.length = n - dC;
return a;
};
}

Finally, a /really/ bare-bones deletion routine would be:

if('function' != typeof Array.prototype .splice) {
Array.prototype .splice = function(s, dC) {
for(var i = 0, n = this.length; i < dC; ++i) {
this[s + i] = this[s + i + dC];
}
this.length = n - dC;
};
}

[snip]

Hope that helps,
Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #2
Michael Winter wrote:
A complete implementation of splice is included below which can
supplement an older browser: [...]


Tell me if I'm wrong, but I think this can be done easier:

if (typeof Array == "function" && typeof Array.prototype .splice != "function") {
Array.prototype .splice = mySplice;
}

function mySplice(p, n) {
var i, j, r = new Array();
if (!isNaN(p) && p>-1 && !isNaN(n) && n>0 && p<this.length) {
for (j=0; j<n; j++) {
r[r.length] = this[p+j];
this[p+j] = this[p+j+n];
}
this.length -= n;
}
for (i=2; i<arguments.len gth; i++) {
this[this.length] = arguments[i];
}
return r;
}

Did I forget anything?

ciao, dhgm
Jul 23 '05 #3

Thanks, I will implement this and try to absorb the "code' to supplement
older browsers.


*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 23 '05 #4
Dietmar Meier wrote:
Michael Winter wrote:
A complete implementation of splice is included below which can
supplement an older browser: [...]
Tell me if I'm wrong, but I think this can be done easier:


Possibly. It was difficult to see past the algorithm description in
the specification to see precisely what was supposed to be
accomplished. At least initially. I was happy enough with what I
eventually produced that I couldn't really be bothered to take it any
further. Anyone is welcome to suggest improvements, but the overall
behaviour of the code cannot change (well, unless you're correcting a
bug :D).

The implementation doesn't quite conform to the specification;
floating-point values for the first two arguments won't be truncated
to integers. Replacing

+? || 0

with

Math.floor(+? || 0)

would cure that, where ? is s and dC.
if (typeof Array == "function" && typeof Array.prototype .splice !=
"function") {
I don't think testing the Array constructor would be necessary, really.
Array.prototype .splice = mySplice;
A function expression would be better. There's no need to introduce a
global identifier when that identifier shouldn't ever be used by
client code.
function mySplice(p, n) {
The main problem with this function is that it doesn't follow the
semantics laid out by the specification, therefore it doesn't serve as
a general replacement. That's why I posted two other versions which
are more specific to the OP's task.
var i, j, r = new Array();
if (!isNaN(p) && p>-1 && !isNaN(n) && n>0 && p<this.length) {
The first few statements in my code make the start and deleteCount
arguments (s and dC, respectively) take sensible values.

First of all, both values are converted to numbers (though they should
be converted to integers, as I mentioned above). If the conversion
leads to NaN, the values are replaced by zero (0). Note that zero is a
valid value for either argument as the splice function can also insert
array elements (so passing zero might be intentional).

If the starting value is negative, it is used to count back from the
end of the array. For example, a value of -1 means "start at the last
element". The starting value is limited to the range [0,length].

The delete count is also limited: it may not be less than zero, nor
can it extend past the end of the array.

I'm afraid that the statement above doesn't allow for any of this.
Neither can the starting value be negative, nor can the delete count
be zero.

[snip]
for (i=2; i<arguments.len gth; i++) {
this[this.length] = arguments[i];
}


I'm afraid this isn't right either. The extra arguments to the
function should be inserted at the starting point. They aren't
unconditionally appended to the array.

[snip]

By all means try again. As I wrote earlier, any improvements (to /any/
code I post) are more than welcome.

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #5
Michael Winter wrote:

[snip]
nI = Math.min(argume nts.length - 2, 0),


That should be a call to the Math.max method.

[snip]

Mike

--
Michael Winter
Replace ".invalid" with ".uk" to reply by e-mail.
Jul 23 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
4322
by: D. Alvarado | last post by:
Hello, I have an array that contains numbers. Each element in the array is guaranteed to be unique. Let's say I have another variable which I know for certain is in the array, but I don't know the position. What's the quickest way for removing that element? I know I could just use a foreach, but I'm sure one of the experts out there has a better way. Thanks, - Dave
3
1691
by: Jim Ley | last post by:
Hi, IE has the ability to setExpressions on stylesheets so you can calculate the value of the css property through script. For various reasons I'm wanting to use a side-effect of this to attach an event to every element of a class in a document (I'm including content from a lot of large 3rd party content, and iterating over the entire DOM searching for the classes and then attaching the event is proving too slow, aswell as being too...
13
2346
by: J. J. Cale | last post by:
I have the following. There must be something less cumbersome without push pop. The function parameter obj is the event.srcElement and has the attributes(properties?) picNum and alb pinned to it. The function is part of a process to delete the selected obj, a photo in this case from the album vis albumArr. TIA Jimbo function Album(albumName) { this.name=albumName; this.paths=new Array(); }
2
1538
by: bmgz | last post by:
I have written a simple function that validates a form based on the form objects' className attribute. The form basically write a "field required" message next to the form element that is blank(and is required). I have implemented all the Regex stuff onload already. function checkRequired(varForm){ var varReturn = true; for(var i=0; i<varForm.length; i++){ if(varForm.elements.className.indexOf('required') != -1 &&\...
9
5098
by: vbportal | last post by:
Hi, I would like to add BitArrays to an ArrayList and then remove any duplicates - can someone please help me forward. I seem to have (at leaset ;-) )2 problems/lack of understanding (see test code below): (a)When adding BitArrays to the ArrayList and then looping through the ArrayList I seem to access only the latest added BitArray and I'm not exactly clear on best way to access each BItArray in the ArrayList (b)When I try to remove...
24
4389
by: RyanTaylor | last post by:
I have a final coming up later this week in my beginning Java class and my prof has decided to give us possible Javascript code we may have to write. Problem is, we didn't really cover JS and what we covered was within the last week of the class and all self taught. Our prof gave us an example of a Java method used to remove elements from an array: public void searchProcess() { int outIt=0;
1
1922
by: CYBER | last post by:
Hello I'm looking for the fastest way to remove an element from an array so the sequence of keys is not changed. For example when i remove an element from this array $tab = Array('a', 'b', 'c');
7
1753
by: Adam Honek | last post by:
Is there a direct way to remove one entry from a one dimensional array? I keep looking but either my eyes are funny or it isn't there. Must we really create a temp array and copy all but 1 of the entries over to delete one entry? All I want to do is remove an entry at a specified index and then have the ubound(array) go down -1.
6
6109
by: Niyazi | last post by:
Hi all, What is fastest way removing duplicated value from string array using vb.net? Here is what currently I am doing but the the array contains over 16000 items. And it just do it in 10 or more minutes. 'REMOVE DUBLICATED VALUE FROM ARRAY +++++++++++++++++ Dim col As New Scripting.Dictionary Dim ii As Integer = 0
0
8707
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9314
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9174
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9015
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7953
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5947
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4464
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4725
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2520
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.