0

Despite of numerous thread on the subject I didn't manage to remove an item of a string based Array using Array.filter method. Here is the filter method in a context of a mutation of 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);
  }
}

The filter method is call but the item is not removed. I ended up using Array.splice method:

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

Could you tell me what I'm doing wrong?

3
  • 5
    filter does not mutate the original array. Commented Dec 6, 2018 at 11:04
  • 2
    As @CertainPerformance said, try state.filters.geologies = state.filters.geologies.filter(elem => !elem.includes(payload)) Commented Dec 6, 2018 at 11:05
  • Not this way Cristian. This way the state.filters.geologies becomes not reactive. Commented Dec 6, 2018 at 11:16

2 Answers 2

2

based on MDN:

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

so basically what is wrong in your code is that:

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

is not being saved in any variable, thus the filtered array isn't being used. in order to make it work you need to assign the return value of the filter. something like:

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

or as vladislav said:

state.filters.geologies = [...state.filters.geologies.filter(elem => !elem.includes(payload))]
Sign up to request clarification or add additional context in comments.

Comments

2

Until splice() method is mutating original array, filter(), map(), or some() methods returns new array and leave the original array intact. So, you can use filter() method, but then you should replace original array with returned array. For example:

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)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.