473,473 Members | 2,304 Online
Bytes | Software Development & Data Engineering Community
Create 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 6346
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(arguments.length - 2, 0),
i, j;
s = (0 > s) ? Math.max(s + n, 0) : Math.min(s, n);
dC = Math.min(Math.max(+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.max(+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.length; 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.length; 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(arguments.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
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...
3
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...
13
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....
2
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...
9
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...
24
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...
1
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',...
7
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...
6
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...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
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...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
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...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

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.