Having trouble with Array.filter functionality

Despite the multitude of discussions on this topic, I have not been successful in using the Array.filter method to remove an item from a string-based Array. Below is an example of the filter method being used in the context of mutating a Vuex store.

UPDATE_FILTERS_GEOLOGIES: (state, payload) => {
  if (state.filters.geologies.some(elem => elem === payload)) {
    state.filters.geologies.filter(elem => !elem.includes(payload))
  } else {
    state.filters.geologies.push(payload);
  }
}

Even though the filter method is called, the item is not removed. I resorted to using the Array.splice method instead:

let position = state.filters.geologies.indexOf(payload);
state.filters.geologies.splice(position, 1)

I am unsure of what I may be doing incorrectly. Can someone please provide guidance?

Answer №1

As stated on the MDN website:

The filter() method generates a fresh array containing all elements that pass the test specified by the provided function.

The issue in your code lies in the fact that:

state.filters.geologies.filter(elem => !elem.includes(payload))

is not stored in any variable, hence the filtered array is not utilized. To resolve this, you need to assign the result of the filter to a variable. For example:

state.filters.geologies = state.filters.geologies.filter(elem => !elem.includes(payload))

or as suggested by vladislav:

state.filters.geologies = [...state.filters.geologies.filter(elem => !elem.includes(payload))]

Answer №2

When using the splice() method, the original array is altered. However, when using methods like filter(), map(), or some(), a new array is returned while leaving the original array unchanged. If you want to make changes using the filter() method, you should update the original array with the returned array. For instance:

UPDATE_FILTERS_GEOLOGIES: (state, payload) => {
  let g = state.filter.geologies
  let p = payload

  g.some(e => e === p)
    ? (g = { ...g.filter(e => !e.includes(p)) })
    : g.push(p)
}

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

Safari iOS 8 experiencing issues with loading WebGL image textures

The example mentioned above runs smoothly on all major browsers, including Safari on Mac OS. However, it fails to display the correct image on my iPad running the latest iOS 8. Click here for the example. Similarly, the tutorial provided in the following ...

Module for Node.js that handles .ini files where variable names can begin with a number

.ini file: [1] 10X=true [2] 10X=true node.js : var mS = ini.parse(fs.readFileSync(__dirname + '/XXX/MS.ini', 'utf-8')); console.log(mS.1.10X); I am utilizing the ini module in node.js, which can be found at this link: https://www.n ...

The intricate dance between JAVA and HTML

Can Java be compatible with HTML and JS? Is it possible for them to cooperate without using JSP? In order to connect the WEKA function, we utilized Java code through a JAR file, but now we also require HTML and JS links for visualization. Is there an alte ...

Improving Page Load Speed with HTML Caching: Strategies for Enhancing Performance when over half of the data transferred is for navigation menus

I manage a complex and expansive website that contains a significant amount of repetitive HTML elements such as the navigation menu and top ribbon. Loading a single page on my site can be resource-intensive, with up to 300KB of data required, half of whic ...

Generate a dynamic text-box and drop-down list using HTML and JavaScript

My current project involves generating dynamic text-boxes based on the selection from a drop-down list and input field. When a user chooses 'Option 1' from the drop-down list and enters input such as 'grass', 'table', etc., t ...

Unable to locate webpack module

When I try to run the command npm run start, I encounter an error message: The webpack configuration is as follows: "name": "frokify", "version": "1.0.0", "description": "frokify project", ...

interrupt the node script using async behavior

I encountered an issue while running the npm install command to install a list of modules on Node, specifically related to async. TypeError: undefined is not a function What could be causing this problem? var fs = require( "fs" ), path = require( ...

Utilizing JQuery toggle feature to display extra content

Having some trouble with my JQuery toggle/collapse function. I added my own class "timelineEventWide" but it's not working as expected. As a JavaScript beginner, could someone please help me with the correct syntax? Thank you! e(".expandAll").toggle( ...

Can we prevent a component from being mounted every time it is rendered by its parent component?

Is it possible to render the Child component within the Father component without mounting it and resetting its states when the Father component is rendered? I attempted to use the useMemo hook to render the Child component, but it still mounts the compone ...

Transferring data files through an ajax-based form submission

I am encountering an issue when trying to send a file to a server using AJAX for submission. Despite attempting various methods involving var xhr = new XMLHttpRequest(); and $.ajax({});, I consistently receive the error message Uncaught TypeError: Illegal ...

How can we optimize axios requests with lodash debounce?

Utilizing a state prop named network busy status to control elements in the UI. Due to the rapid changes in status, my spinner appears overly active. Is there a simple method, utilizing lodash _.debounce, to throttle this section of code? const instance ...

Top tips for writing JavaScript that incorporates an AJAX call to determine whether the default action should be blocked

Utilizing JavaScript and jQuery, I am developing a handler for form submission that will either allow or prevent the form from being submitted based on certain conditions. Although this task is fairly straightforward, it becomes more complex due to the ne ...

Determining the number of words in every line within a textarea

I am looking to determine the number of words per line in a textarea. The width of the textarea is variable. Check out this code snippet that calculates the number of rows: http://jsfiddle.net/2tcygj9e/ ...

Is there a way to implement JavaScript within my Blazor server razor page to modify the styling of a blazor bootstrap button after a form submission?

I am currently working on a Blazor server application where I am looking to add a special functionality. My goal is to have the accordion header change to red if validation fails, meaning if there is no input in the field. view image here //index.razor pa ...

Blog entries alternating between a pair of distinct hues

I want to create a design where each post container has a different color from the one next to it. Essentially, I would like the containers to alternate between two distinct colors. The left side shows how it currently appears, while the right side depict ...

The $route object in vue-router appears to be empty when used with single file components

I am facing an issue while using single file components with vue-router and vue-2.0. The problem I can't seem to resolve is that the this.$route object, when called from a component, always returns empty values. For example: Messages.vue <te ...

Issue with .env file access token: Successfully working for one API in Next.js, but failing for

I am utilizing two different APIs, WordsAPI and Spotify API. Each API requires an access token or key which I have stored in a secure .env file. I have successfully fetched data from WordsAPI using the same method in getStaticProps, but I am facing issues ...

Array in Javascript reset to null after its second iteration

''' const users = [] const addUser = ({ id, username, room }) => { // Clean the data username = username.trim().toLowerCase() room = room.trim().toLowerCase() // Validate the data if (!username || !room) { r ...

Tips for concealing subsequent pages and displaying pagination in jQuery ajax response

Is there a way to display pagination based on a limiter in an ajax response? For example, if the limiter is set to 5, only show 10 page links and hide the rest. 1 2 3 4 5 6 7 8 9 10 .. next 11 12 13 14 15.. next I attempted to count the li elements in ...

Verify that the computer is connected to the Internet by sending an ajax request to Google

Whenever I need to test my internet connection, I rely on the following code snippet: const checkInternetConnection = () => { $('input').ajaxError(function(){ alert("failed"); }); $.get('http://www.google.com', f ...