Ashley Connolly
Ashley Connolly

Reputation: 15

Using Javascript's filter function

I will do my best to word this correctly - thanks for any help.

I have an array with a series of postcodes in them, (six for example) one of which will be empty. Using javascripts filter function, I removed the element that was empty using the following code:

var filteredrad = radius1.filter(function(val) {
  return !(val === "" || typeof val == "undefined" || val === null);
});

Now I need to somehow store the index of which element(s) were removed from the original array, but im unsure on how to.

As an example, the filter would remove the space at index 1. How do I save that number one for use later on?

["WC1A 1EA", "", "B68 9RT", "WS13 6LR", "BN21TW", "wv6 9ex"] 

Hope that makes sense, any help would be greatly appreciated.

Ashley

Upvotes: 0

Views: 280

Answers (4)

SoEzPz
SoEzPz

Reputation: 15922

Just another example that does what you wish in another way

var collection = ["WC1A 1EA", "", "B68 9RT", "WS13 6LR", "BN21TW", "wv6 9ex"] ;

var postalCodes = (function(){
  var emptyIndices;

  return {
    getCodes: function( array ){
      emptyIndices = [];
      return array.filter(function( value, index, array ){
        if( !value ){
          emptyIndices.push(index);
          return false;
        }else{
          return true;
        }
      });
    },
    getEmptyIdices: function(){
      return emptyIndices || null;
    }
  };
})();

Then just call

postalCodes.getCodes(collection);
=> ["WC1A 1EA", "B68 9RT", "WS13 6LR", "BN21TW", "wv6 9ex"];

postalCodes.getEmptyIndices();
=> [1];

Upvotes: 0

Cathal
Cathal

Reputation: 1790

radius1 = ["WC1A 1EA", "", "B68 9RT", "WS13 6LR", "BN21TW", "wv6 9ex"];
removed = [];
var filteredrad = radius1.filter(function(val, index) {
  if (val === "" || typeof val == "undefined" || val === null) {
    removed.push(index); 
    return false;
  }
  return true;
});

Upvotes: 0

gusridd
gusridd

Reputation: 884

The filter function passes three arguments to the callback function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

So you could write:

var storedIndexes = []
var filteredrad = radius1.filter(function(val, index) {
  val isNull = (val === "" || typeof val == "undefined" || val === null);
  if(isNull){
    storedIndexes.push(index);
  }
  return !isNull;
});

And have the indexes saved in storedIndexes

Upvotes: 0

Jean-Karim Bockstael
Jean-Karim Bockstael

Reputation: 1405

You can use a side-effect, using filter's second argument:

var removed = [];
var filteredrad = radius1.filter(function(val, index) {
    if (val === "" || typeof val == "undefined" || val === null) {
        removed.push(index);
        return false;
    }
    return true;
});

Upvotes: 5

Related Questions