Remove array items iteratively

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Derek Basch

    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

  • Stephen Chalmers

    #2
    Re: Remove array items iteratively

    Derek Basch <dbasch@yahoo.c om> wrote in message
    news:1109205136 .758427.262560@ g14g2000cwa.goo glegroups.com.. .[color=blue]
    > 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
    >[/color]
    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.



    Comment

    • Jarmo

      #3
      Re: Remove array items iteratively

      "Derek Basch" <dbasch@yahoo.c om> wrote in message
      news:1109205136 .758427.262560@ g14g2000cwa.goo glegroups.com.. .[color=blue]
      >
      > 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?[/color]

      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.


      Comment

      • RobB

        #4
        Re: Remove array items iteratively

        Derek Basch wrote:[color=blue]
        > 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[/color]
        splice.[color=blue]
        >
        > How do I iterate though an array, remove items AND change the length
        > property?
        >
        > Thanks,
        > Derek Basch[/color]

        <!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>

        Comment

        • Douglas Crockford

          #5
          Re: Remove array items iteratively

          > I can remove objects from an array by doing this:[color=blue]
          >
          > 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?[/color]

          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

          Comment

          • Derek Basch

            #6
            Re: Remove array items iteratively


            Douglas Crockford wrote:
            [color=blue]
            > You should not be using an array if the subscripts are not integers.
            > That is what objects are for.[/color]

            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

            Comment

            • Douglas Crockford

              #7
              Re: Remove array items iteratively

              >>You should not be using an array if the subscripts are not integers.[color=blue][color=green]
              >>That is what objects are for.[/color]
              >
              >
              > 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
              > };[/color]

              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

              Comment

              • Derek Basch

                #8
                Re: Remove array items iteratively

                Douglas Crockford wrote:
                [color=blue]
                > I can't make sense of this. What are you trying to do?[/color]

                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

                Comment

                Working...