Having difficulty applying a filter to an array following the deletion of an element in a class method

I'm having trouble filtering my array using a filter function. I need to get an updated, filtered array. If there is a way to improve the code, please advise on what changes can be made.

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',
]);

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

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

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

Answer №1

The filter() method generates a fresh array containing only elements that pass the specified function's test.

In order to do this, you can either assign the value of this._items as follows:

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

Alternatively, you can directly return the result of this._items.filter() like so:

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

Answer №2

When using .filter(), it's important to remember that it doesn't modify the original array, but instead creates a new one. Make sure to assign the result back to your array.

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

Alternatively, you can remove a single item from an array using .splice().

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

Answer №3

.filter creates a fresh array, without altering the original one. Give this a shot:

class Warehouse {
    constructor(products) {
      this._products = products;
    }
    getProducts() {
      return this._products;
    }
    addProduct(product) {
      this._products.push(product);
      return this._products;
    }
    removeProduct(product) {
      const updatedList = this._products.filter(value => value != product);
      return updatedList;
    }
  }

  let inventory = new Warehouse([
    'Apples',
    'Oranges',
    'Bananas',
    'Berries',
  ]);

  let stock = inventory.getProducts();
  console.table(stock);

  inventory.addProduct('Grapes');
  console.table(stock);

  inventory.removeProduct('Bananas');
  console.table(stock);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

jquery counter is malfunctioning

I noticed a strange issue with the counters on my website. They count up as expected when the page loads, but for some reason, when the screen width shrinks below 800px, they don't start automatically. However, if I quickly scroll to where the counter ...

Condition in Bash script for verifying JSON response

This particular script is designed to notify me whenever there is an error response. Problem: Even when the execution is successful, I am still receiving an email. Bash script: #!/bin/bash DATA=$(wget --timeout 5 -O - -q -t 1 http://this.url/?parm=1&bs ...

Exploring the power of SimpleXML in PHP with Array manipulation

As I execute this code: foreach($xml->movie as $movie) { if(isset($movie->photos)) { foreach ($movie->photos as $photo) { echo $photo."&nbsp;"; } echo "<hr/>"; } } I'm able to see ...

Arrange an array of objects based on boolean values first, followed by numerical values in JavaScript

I am facing a challenge where I have an array of objects that need to be sorted based on two rules, following a specific order: Firstly, objects with the "departeYet" property set to true should come first. Secondly, the objects must then be sorted numeri ...

Tips for transforming a scroll element into the viewport using Angular 2+

This is a sample Here is a component with a list of items: class HomeComponent { text = 'foo'; testObject = {fieldFirst:'foo'}; itemList = [ '1', '2', '3', & ...

Code in JavaScript that shows only a portion of the selected option in a dropdown menu

I'm just starting to learn Javascript and I'm looking to create a script for a select tag that displays countries and their phone codes. My goal is to have the dropdown menu show both the country and code, but once the user selects an option, onl ...

Unable to locate the value property of a null object

I'm currently working on creating a Shopping Cart using HTML, CSS, JavaScript, and JQuery. The idea is that when you click "Add to Cart" for the orange item, most of the HTML elements will disappear, leaving only the table displaying the Shopping Cart ...

Implementing access restrictions for modules in NodeJS

In Node, is it possible to limit access or permit access only to specific modules from a particular module? Should I consider replacing the require function and object in the global scope for this purpose? I have concerns about the security of a certain mo ...

What is the method for showcasing an image before it has been uploaded?

I must start by apologizing for my English, as I am not the most fluent speaker. Here's where I'm facing a dilemma: I have created an application that allows users to edit questions for a game. These questions are stored on a server and can be ...

Angular Oops! We ran into a small hiccup: [$injector:modulerr]

I am facing an issue with an angular js error angular.js:36 Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.2.19/$injector/modulerr?p0=app&p1=Error%3A%20…gleapis.com%2Fajax%2Flibs%2Fangularjs%2F1.2.19%2Fangular.min.js%3A18%3A139) ...

Can we utilize object properties in this manner?

Hey there! I've been experimenting with the react-bootstrap library recently, trying to get better at using it. While going through the tutorial, I came across some ES6 code that caught my attention. function FieldGroup({ id, label, help, ...props } ...

Delete the generated thumbnails from the input JavaScript file

One issue I'm facing is that I have written JavaScript code to generate a thumbnail when a user uploads an image. Now, I would like to implement a feature that allows the user to click on an "X" button to delete the uploaded image. This is the existi ...

Concealing Website Elements with javascript based on class assignments

Despite my hesitation, I have to ask this question after unsuccessful searches in related articles. In my code, I have 7 nav links all with the same class. Due to the length of the HTML, I am looking for a way to hide contents until the link is clicked, an ...

Troubleshooting Safari compatibility issues with Twitter Direct Messages in Angular

I am attempting to create a Twitter direct message with predetermined text already filled in. My current method involves using window.open() to prepare the message. window.open(https://twitter.com/messages/compose?text=${this.helloWorld}); helloWorld = ...

What is the best way to retrieve content from a different website using javascript in an asp.net environment?

Currently working on a web application in asp.net where I want to provide users with a JavaScript code that allows them to fetch content from my website and display it on their own website. To handle user requests on my website, I have implemented a gener ...

Omit certain components from the JQuery ListNav plugin

I recently incorporated the Jquery plugin for record filtration. I obtained this plugin from the following link: After successfully implementing the plugin, I encountered an issue where it was counting the headings along with the alphabet filters in my co ...

Displaying a dropdown selection that showcases two object properties lined up side by side

I need the select option dropdown values to display employee names along with their titles in a lined up format. For instance, if my values are: Bob Smith Director Mike Kawazki HR Jane Doe Manager I want them to be shown as: Bob Smith Director Mi ...

Align images at the center of a division using the Bootstrap framework

I'm facing an issue with centering social network icons under a div in my login form while keeping it responsive. Can someone please assist me with this problem? Please help me!!. .row { background: #f8f9fa; margin-top: 20px; } .col { bor ...

Tips for storing an array of strings in a JSON file using Javascript

Is it possible to save an array of strings to a JSON file using Node.js? const alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']; example.json [ "a", "b&q ...

There seems to be a disconnect between the React Redux store

When attempting to connect my store to a React application, I encountered the following error: TypeError: state is undefined store/index.js (Creating Reducer function) import {createStore} from 'redux'; const counterReducer = (state:{counter:0} ...