简体   繁体   中英

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

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;
});

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

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;
});

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM