简体   繁体   English

无法正确Array.filter

[英]Cannot Array.filter properly

Despite of numerous thread on the subject I didn't manage to remove an item of a string based Array using Array.filter method. 尽管在这个主题上有很多话题,但我还是无法使用Array.filter方法删除基于字符串的Array Array.filter Here is the filter method in a context of a mutation of a Vuex store. 这是Vuex商店发生变异时的过滤方法。

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. filter方法是call,但未删除该项目。 I ended up using Array.splice method: 我最终使用Array.splice方法:

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

Could you tell me what I'm doing wrong? 你能告诉我我在做什么错吗?

Until splice() method is mutating original array, filter(), map(), or some() methods returns new array and leave the original array intact. 在splice()方法使原始数组发生变异之前,filter(),map()或some()方法将返回新数组并保持原始数组不变。 So, you can use filter() method, but then you should replace original array with returned array. 因此,您可以使用filter()方法,但随后应使用返回的数组替换原始数组。 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)
}

based on MDN: 基于MDN:

The filter() method creates a new array with all elements that pass the test implemented by the provided function. filter()方法创建一个新数组,其中所有元素都通过了由提供的函数实现的测试。

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 . 为了使其工作,您需要分配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))]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM