0

I have function, which on change calling method 'saveSelectedValue'.

  this.$filtercat.on('change', { that : this }, this.saveSelectedValue);

This method does only one thing: saving data in array.

  saveSelectedValue : function (e) {
    var that = e.data.that,
    selectArray = that.filterSelectedCategories;
    selectArray.push($('.posts-filter-cat').val());
    console.log(selectArray); //every time gives me extended array  
},

Now I am adding new value to the existing array. But I want to delete everything and add new value in array on every change.

max
  • 108
  • 1
  • 7

1 Answers1

0

You need to clear array before pushing new value. Easy way to remove all exisiting values is to set length to 0:

saveSelectedValue : function (e) {
    var that = e.data.that,
    selectArray = that.filterSelectedCategories;
    selectArray.length = 0; // clear selectArray array
    selectArray.push($('.posts-filter-cat').val());
    console.log(selectArray);
},
dfsq
  • 191,768
  • 25
  • 236
  • 258
  • 1
    Couldn't most of that be compressed to: `that.filterSelectedCategories; = [$('.posts-filter-cat').val()]`? – Cerbrus Nov 26 '15 at 07:45
  • 1
    @Cerbrus Maybe, but then it will overwrite filterSelectedCategories array and reference will be broken. Not sure what framework OP's using, but it may cause problems. – dfsq Nov 26 '15 at 07:46
  • It could be the same thing, if I know that I have only 1 item in array. selectArray.splice(0,1); Right? – max Nov 26 '15 at 07:46
  • @max: You don't even have to know there's only one item: `selectArray.splice(0, selectArray.length, $('.posts-filter-cat').val());` – T.J. Crowder Nov 26 '15 at 07:47