473,785 Members | 2,435 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Remove array items iteratively

I can remove objects from an array by doing this:

for (i in oCache){
if (i == "test"){
delete oCache[i];
};
};

However, the array's length property is unaffected.

If I use splice like so:

for (i in oCache){
if (i == "test"){
oCache.splice(i , 1);
};
};

It breaks because oCache's length is altered within the loop by splice.

How do I iterate though an array, remove items AND change the length
property?

Thanks,
Derek Basch

Jul 23 '05 #1
7 6483
Derek Basch <db****@yahoo.c om> wrote in message
news:11******** **************@ g14g2000cwa.goo glegroups.com.. .
I can remove objects from an array by doing this:

for (i in oCache){
if (i == "test"){
delete oCache[i];
};
};

However, the array's length property is unaffected.

If I use splice like so:

for (i in oCache){
if (i == "test"){
oCache.splice(i , 1);
};
};

It breaks because oCache's length is altered within the loop by splice.

How do I iterate though an array, remove items AND change the length
property?

Thanks,
Derek Basch

If you test the length on each iteration, it won't matter if it changes:

for (var i=0; i<oCache.length ; i++)
if (i == "test")
oCache.splice(i , 1);

--
S.C.

Jul 23 '05 #2
"Derek Basch" <db****@yahoo.c om> wrote in message
news:11******** **************@ g14g2000cwa.goo glegroups.com.. .

It breaks because oCache's length is altered within the loop by splice.

How do I iterate though an array, remove items AND change the length
property?


The simplest way to do this is to iterate from bottom to top rather than top
to bottom. For example:

for (ii = blob.length - 1; ii >= 0; ii--)
{
if (blob[ii] meets some condition)
{
remove blob[ii] from array
}
}

This way the changing value of blob.length has no impact, nor does the
removal of items from the array.
Jul 23 '05 #3
Derek Basch wrote:
I can remove objects from an array by doing this:

for (i in oCache){
if (i == "test"){
delete oCache[i];
};
};

However, the array's length property is unaffected.

If I use splice like so:

for (i in oCache){
if (i == "test"){
oCache.splice(i , 1);
};
};

It breaks because oCache's length is altered within the loop by splice.
How do I iterate though an array, remove items AND change the length
property?

Thanks,
Derek Basch


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>untitled </title>
<script type="text/javascript">

Array.prototype .dele = function()
{
for (var i = 0, l = arguments.lengt h, arr = []; i < l; ++i)
{
for (var j = 0; j < this.length; ++j)
{
if (this[j] == arguments[i]
&& typeof this[j] == typeof arguments[i])
{
arr.push(this.s plice(j, 1));
}
}
}
return arr;
}
var oCache = [
'el1' , 'el2' , '3' , 'test1' , 'el4' , 'test2'
];

a = window.alert;
a('oCache:\n\n' + oCache.join('\n '));
a('original length: ' + oCache.length);
a('call: oCache.dele(\'t est1\')');
a('element removed: ' + oCache.dele('te st1'));
a('oCache:\n\n' + oCache.join('\n '));
a('oCache length: ' + oCache.length);
a('call: oCache.dele(\'t est2\')');
a('element removed: ' + oCache.dele('te st2'));
a('oCache:\n\n' + oCache.join('\n '));
a('oCache length: ' + oCache.length);
a('call: oCache.dele(3)' );
a('element removed: ' + oCache.dele(3)) ;
a('oCache:\n\n' + oCache.join('\n '));
a('oCache length: ' + oCache.length);
a('call: oCache.dele(\'e l1\', \'el2\', \'3\', \'el4\')');
a('elements removed: ' + oCache.dele('el 1', 'el2', '3', 'el4'));
a('oCache:\n\n' + oCache.join('\n '));
a('oCache length: ' + oCache.length);

</script>
</head>
<body>
</body>
</html>

Jul 23 '05 #4
> I can remove objects from an array by doing this:

for (i in oCache){
if (i == "test"){
delete oCache[i];
};
};

However, the array's length property is unaffected.

If I use splice like so:

for (i in oCache){
if (i == "test"){
oCache.splice(i , 1);
};
};

It breaks because oCache's length is altered within the loop by splice.

How do I iterate though an array, remove items AND change the length
property?


You should not be using an array if the subscripts are not integers.
That is what objects are for.

The array.length property is supposed to be 1 larger than the largest
integer subscript. The array.splice method has no effect on array.test.

If you misuse language features, you can easily get confused.

Perhaps your example is wrong, and you really are dealing with integer
subscripts. (There is a difference between test and "test".) In that
case, loop through backwards.

for (i = oCache.length - 1; i >= 0; i -= 1) {

See http://www.crockford.com/javascript/survey.html
Jul 23 '05 #5

Douglas Crockford wrote:
You should not be using an array if the subscripts are not integers.
That is what objects are for.


Ahhh right, I always forget that. My question now is how do I test for
the existence of child objects if I cant test for something like
length? Here is what I currently am using but it seems kludgy.
for (var i in filter_cache){
if (filter_cache[i]){
var flag = true
};
};

if (flag != true) {
var a = getCache(sSortT ype, nColumn);
}
else {
var a = filter_cache
};
dTb

Jul 23 '05 #6
>>You should not be using an array if the subscripts are not integers.
That is what objects are for.

Ahhh right, I always forget that. My question now is how do I test for
the existence of child objects if I cant test for something like
length? Here is what I currently am using but it seems kludgy.
for (var i in filter_cache){
if (filter_cache[i]){
var flag = true
};
};

if (flag != true) {
var a = getCache(sSortT ype, nColumn);
}
else {
var a = filter_cache
};


I can't make sense of this. What are you trying to do?

It is bad to define a var twice in the same function.
Also, (flag != true) is better written as (!flag).
Also, for and if should not be followed by semicolon.
See http://www.crockford.com/javascript/lint.html
Jul 23 '05 #7
Douglas Crockford wrote:
I can't make sense of this. What are you trying to do?


Not suprising since I totally hosed my example code. Sorry. It Should
be:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitl ed Document</title>
<meta http-equiv="Content-Type" content="text/html;
charset=iso-8859-1">
</head>
<body>

<script language="javas cript" type="text/javascript">

function findChildObject s(){
var filter_cache = Object;
var child_object = Boolean;

filter_cache.fi lter_1 = {
type: "Keyword"
};
filter_cache.fi lter_2 = {
type: "Substring"
};

for (var i in filter_cache){
if (typeof(filter_ cache[i]) === "object"){
child_object = true;
}
}
if (child_object === true) {
alert("Children exist");
}
else {
alert("Children don't exist");
}
}

findChildObject s();

</script>

</body>
</html>

Is there a better way to test for the existence of child objects?

dTb

Jul 23 '05 #8

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

Similar topics

2
2467
by: Patrick G. | last post by:
Greetings all: ASP VB, SQL Svr 2000 I am pulling data from 3 tables. table1 holds item details table2 holds publication types and the item id from table1 table3 holds category types and the item id from table1
12
55571
by: Sam Collett | last post by:
How do I remove an item with a specified value from an array? i.e. array values 1,2,2,5,7,12,15,21 remove 2 from array would return 1,5,7,12,15,21 (12 and 21 are NOT removed, duplicates are also removed) So far I have (val is value, ar is array, returns new array):
0
341
by: choyk1 | last post by:
I intended to save properties of an object to a Hashtable. In this case, keys and values are not fixed types and I cannot use SortedList. I have no idea what order the .NET framework add items to Hashtable when Add(key, value) method is applied. Monitoring the position items are added, I cannot find if key is the standard or value. I thought basically Hashtable function acts randomly, therefore the order will be changed unexpectedly. ...
3
3810
by: Don | last post by:
My user control has a combobox with an arraylist attached to it along with custom add and remove methods. The "Add" method is working great. However I don't understand why the "Remove" method isn't working. It neither removes the item from the arraylist nor from the combobox like it's supposed to do. A couple of notes: cbx is the name of the combobox within my usercontrol, file is the name of the arraylist within my usercontrol. To try...
2
6307
by: Mamatha | last post by:
Hi I have an application with listview.When i click on one button the data will be displayed like this in the listview: colA colB colC ----- ----- ------ nannacom.com 0 0 When i click on another button,i want to display like this
3
6051
by: Bill Nguyen | last post by:
I use the following example (from another post) and it seemed to work fine. However, when I add the syntax to remove the selected item from the senderbox, I got error. senderBox.Items.RemoveAt(senderbox.selectedIndex) I was told that I need to copy selecteditems to an array and run the For each routine from the array instead. Can someone please give me some idea on how to accomplish this? Thanks a million.
19
6335
by: brasilino | last post by:
Hi Folks: I've been looking (aka googling) around with no success. I need a usability beyond 'pop()' method when removing an Array elements. For example: oName = new Array('Lucas','Brasilino','Silva'); oName.remove('Brasilino'); oName.toString(); // puts out 'Lucas,Silva'
7
7423
by: Jacob JKW | last post by:
I need to iterate over combinations of n array elements taken r at a time. Because the value of r may vary quite a bit between program invocations, I'd like to avoid simply hardcoding r loops. I assume the best way to do this would be either using closures or creating some sort of iterator class. Any guidance on how to get started? Thanks,
10
6771
by: pamelafluente | last post by:
Hi I have a sorted list with several thousands items. In my case, but this is not important, objects are stored only in Keys, Values are all Nothing. Several of the stored objects (might be a large number) have to be removed (say when ToBeRemoved = true). class SomeObj ToBeRemoved be a boolean field end class
0
9645
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10147
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...
1
10091
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8972
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...
1
7499
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6739
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
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2879
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 can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.