Page 1 of 1

Stupid JS question

Posted: Sun May 28, 2017 7:50 pm
by KyleMassacre
Anyone who knows me knows that JS is not my strong suit but lately I have been forcing myself to work with it a lot more. I have a question about filter().

Let's say I have a simple array and each index of the array has several properties. What I would like to do is filter the array but be able to reverse the filter back to its normal state so I can apply other filters based on the original array without calling the database again to either get the original state or apply the filter(s) I want. Also note that I don't want to install a 3rd party package so let's try to act like that is not an option.

If have tried stuff like:

Code: Select all

var negate = function(cb) {
  return function() {
    return !cb.apply(this,arguments);
  }
};

var myFilter = function(m) {
  return m.someProp === "someString";
};

function applyFilter() {
  myArray.filter(myFilter);
}

function revertFilter() {
  myArray.filter(negate(myFilter));
}
The 'revertFilter' function basically erases my entire array when I call it.

Re: Stupid JS question

Posted: Mon May 29, 2017 3:24 am
by a_bertrand
The issue is that the .filter function creates a new array with only the entries which match the filter. So your reset should just return the original array not try to further filter the array. To do so, simply keep the original array somewhere. You may use .slice() to duplicate the array (warning it's not a deep copy).

Re: Stupid JS question

Posted: Mon May 29, 2017 3:54 am
by KyleMassacre
So basically you are saying to do something like:

Code: Select all

var myClass = new (class
{
  public mainArray: SomeType[];
  public cacheArray: SomeType[];
}
....
static GetData() {
  $.ajax({'...'},
  success: function(data) {
    myClass.mainArray = data;
    myClass.cachedArray = data;
  }
  ....
}
static ApplyFilter() 
{
  return myClass.mainArray.filter(myFilter); // used from my first post
}

static RevertFilter()
{
  myClass.mainArray = myClass.cachedArray;
  return myClass.mainArray;
}

Re: Stupid JS question

Posted: Mon May 29, 2017 2:24 pm
by a_bertrand
I think you are somewhat having issues with pointers here, even if in any modern language you don't see them anymore any code still rely on it ;)

Code: Select all

var myClass = new (class
{
  public mainArray: SomeType[];
  public cacheArray: SomeType[];
}
....
static GetData() {
  $.ajax({'...'},
  success: function(data) {
    myClass.mainArray = data.slice();
    myClass.cachedArray = data.slice();
  }
  ....
}
static ApplyFilter() 
{
  return myClass.mainArray.filter(myFilter); // used from my first post
}

static RevertFilter()
{
  myClass.mainArray = myClass.cachedArray.slice();
  return myClass.mainArray;
}