[英]Array.prototype.filter - Is it possible to filter multiple conditions with more than one criteria? [JS, VueJS]
I have the following method on VueJS 2.0/Nuxt Application:我在 VueJS 2.0/Nuxt 应用程序上有以下方法:
applyFilters(filterCriteria) {
this.filtered = this.unfiltered.slice().filter((x) => {
// Zona
if (x.zona !== filterCriteria.zona) {
return false
}
// Bairro
for (const key in filterCriteria.bairro) {
if (x.bairro !== filterCriteria.bairro[key]) {
return false
}
}
// Categoria
for (const key in filterCriteria.categoria) {
if (x.categoria !== filterCriteria.categoria[key]) {
return false
}
}
return true
})
},
What I am trying to achieve is somehow filter multiple conditions based also on multiple criteria.我想要实现的是基于多个条件以某种方式过滤多个条件。 Is that achievable with
.filter()
?这可以通过
.filter()
实现吗?
Whenever I apply the first criteria it works fine, and also when I apply the second it will work as well, but whenever I apply a second item to the second criteria, it just fails to filter and fallback to false
everytime.每当我应用第一个条件时它都可以正常工作,当我应用第二个条件时它也可以正常工作,但是每当我将第二个项目应用于第二个条件时,它每次都无法过滤并回退到
false
。
This works:这有效:
filterCriteria: {
zona: 'Germany',
bairro: ['Berlin'],
categoria: ['City']
}
This won't:这不会:
filterCriteria: {
zona: 'Germany',
bairro: ['Berlin', 'Munich'],
categoria: ['City']
}
Am I missing something or this won't work as expected?我是不是遗漏了什么,或者这不会按预期工作?
You can use includes().您可以使用includes()。 Array and String contains this method
Array 和 String 包含此方法
applyFilters(filterCriteria) {
this.filtered = this.unfiltered.slice().filter((x) => {
// Zona
if (x.zona !== filterCriteria.zona) {
return false
}
// Bairro
if (!filterCriteria.bairro.includes(x.bairro)) {
return false
}
// Categoria
if (!filterCriteria.categoria.includes(x.categoria)) {
return false
}
return true
})
},
The reason is原因是
for (const key in filterCriteria.bairro) {
if (x.bairro !== filterCriteria.bairro[key]) {
return false
}
}
you can't have one value equal to two different values.你不能让一个值等于两个不同的值。
That is, you can't have one value equal to 'Berlin'
and then also equal to 'Munich'
.也就是说,不能有一个值等于
'Berlin'
又等于'Munich'
。 So it will fail for sure.所以肯定会失败。 Looks like the third check is going to have the same issue.
看起来第三次检查也会有同样的问题。
You can use includes
, or another way is您可以使用
includes
,或者另一种方式是
if (!filterCriteria.bairro.some(v => v === x.bairro))
return false;
and just a note: if you have a large array, you can use a Set
instead so that the checking is fast.只是一个注意事项:如果你有一个大数组,你可以使用
Set
来代替,以便检查速度很快。 It is like myCities.has(thisCity)
and it is O(1)
time.它就像
myCities.has(thisCity)
并且是O(1)
时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.