Unable to filter an array after removing an element in a class method

Viewed 51

I can't filter my array using a filter function. There is a need to get an updated, filtered array. If I can upgrade it somehow, please let me know what I can change in the code.

class Store {
  constructor(items) {
    this._items = items;
  }
  getItems() {
    return this._items;
  }
  addItem(item) {
    this._items.push(item); 
    return this._items;
  }
  removeItem(item) {
    this._items.filter(value => value != item);
    return this._items;
  }
}

let storage = new Store([
  'Cubbage',
  'Garlice',
  'Sauce',
  'Tomato',
]);

let items = storage.getItems(); 
console.table(items);

storage.addItem('banana'); 
console.table(items);

storage.removeItem('Tomato');
console.table(items); // 
3 Answers

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

So, either you need to set the this._items like:

removeItem(item) {
    this._items = this._items.filter(value => value != item);
    return this._items;
}

Or, simply return the this._items.filter() method like:

removeItem(item) {
    return this._items.filter(value => value != item);
}

class Store {
  constructor(items) {
    this._items = items;
  }
  getItems() {
    return this._items;
  }
  addItem(item) {
    this._items.push(item);
    return this._items;
  }
  removeItem(item) {
    this._items = this._items.filter(value => value != item);
    return this._items;
  }
}

let storage = new Store(['Cubbage','Garlice','Sauce','Tomato']);

storage.addItem('banana');
let items = storage.removeItem('Tomato');
console.log(items); //

Well .filter() doesnt change your array it just creates a new array. you need to assign it to your array.

this._items = this._items.filter(value => value != item);

To remove a single item you could also use .splice()

  removeItem(item) {
    this._items.splice(this._items.indexOf(item), 1);
    return this._items;
  }

.filter creates a new array, it does not modify the existing one. Try this:

class Store {
    constructor(items) {
      this._items = items;
    }
    getItems() {
      return this._items;
    }
    addItem(item) {
      this._items.push(item);
      return this._items;
    }
    removeItem(item) {
      const res =this._items.filter(value => value != item);
      return res;
    }
  }

  let storage = new Store([
    'Cubbage',
    'Garlice',
    'Sauce',
    'Tomato',
  ]);

  let items = storage.getItems();
  console.table(items);

  storage.addItem('banana');
  console.table(items);

  storage.removeItem('Tomato');
  console.table(items);

Related