4 Replies Latest reply on Jan 10, 2008 9:51 AM by Handycam

    Excluding an empty array?

    Handycam Level 1
      Three optional steps in my project each produce an array of items. I need to combine the arrays into 1, which I was doing with:
      var _combinedAddIns:Array = _vegMeat.concat(_cheeses,_freshHerbs,_spices);

      However, if one of the arrays held no choices (they were optional) the new array contains a "null", and I don't want this.

      I know I can test the arrays for length > 0, but what's the easiest way to do that here?
        • 1. Re: Excluding an empty array?
          m_hartnett Level 3
          There are a few ways to do this.
          This uses a ternary operator to determine if the array should be used. If it does not meat the condition then just return an empty array. The empty array adds nothing to the concat array.

          var _combinedAddIns:Array = _vegMeat.concat(((_cheeses != null) ? _cheeses : new Array()),
          ((_freshHerbs != null) ? _freshHerbs : new Array()),
          ((_spices != null) ? _spices : new Array()));

          You could also put all your arrays into an ArrayCollection and loop through the collection examining if the array is null, if not then concat it the other array.
          • 2. Excluding an empty array?
            Handycam Level 1
            I like it , but I'm confused by the new Array() part.

            I get "if _spices is not null then _spices, otherwise" but why is the otherwise creating a new array?

            For now I've done:
            _combinedAddIns = _vegMeat.concat(_cheeses);
            if (_freshHerbs != null){
            _combinedAddIns = _combinedAddIns.concat(_freshHerbs);
            }
            if (_spices != null){
            _combinedAddIns = _combinedAddIns.concat(_spices);
            }
            • 3. Re: Excluding an empty array?
              m_hartnett Level 3
              a ternary operator requires three arguments:
              (condition) ? conditionMet : conditionNotMet

              Your condition is 'is array null'
              conditionMet is return the array
              conditionNotMet then return a new Array

              ((_cheeses != null) ? _cheeses : new Array()),


              Since the new array is empty the concat of it is meaningless. Nothing is added. It is used only as a 'trick' to return something that is not null.
              • 4. Re: Excluding an empty array?
                Handycam Level 1
                Ah, now I see. Thanks.