在平面图中结合两种过滤条件



我有一个过滤方法,看起来像这个

Object.values(state.storeLayout.items).flatMap((level) => 
level.poi?.filter((x) => 
(x.guid === guid)) ?? []).map((poi) => poi.coordinate)

然而,我也想做:

Object.values(state.storeLayout.items).flatMap((level) => 
level.portals?.filter((x) => 
(x.guid === guid)) ?? []).map((poi) => poi.coordinate)

我的问题是如何连接两种过滤方法

level.portals?.filter((x) => 
(x.guid === guid)) ?? [])
level.poi?.filter((x) => 
(x.guid === guid)) ?? [])

内部flatMap,所以我只有一个功能

所以基本上像这个

Object.values(state.storeLayout.items).flatMap((level) => 
level.poi?.filter((x) => 
(x.guid === guid)
&& 
level.portal?.filter((x) => 
(x.guid === guid)
) ?? []).map((poi) => poi.coordinate)

也许是这样的?

Object.values(state.storeLayout.items).flatMap((level) => {
let tmpLevel = {...level}
tmpLevel.portal = tmpLevel.portal?.filter((x) => (x.guid === guid) ?? []
tmpLevel.poi = tmpLevel.poi?.filter((x) => (x.guid === guid)) ?? []
return tmpLevel
} ?? []).map((poi) => poi.coordinate)

就像@KiraLT提到的那样,如果您提供所需的输入和输出会更容易,但处理这一问题的一种方法是使用reduce。

背景:

  • 在JS中,函数是一流的,这意味着它们可以作为参数传递给其他函数。(https://developer.mozilla.org/en-US/docs/Glossary/First-class_Function)
  • 可以从对象中销毁值或属性(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)
  • 减少";逐个元素遍历数组,在每一步都将当前数组值添加到上一步的结果中(此结果是所有前一步的运行总和(,直到没有更多的元素可添加为止"(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)在这种情况下,我们可以设置一个回调函数数组和初始值,即应该传递给第一个函数的param
  • flatMap基本上是map,然后是flat。(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap)

这可能和你的fn性能差不多,所以要谨慎对待。

function flatMapStoreItems() {
const guid = W/E

function filterPortals(items) {
return items.portals?.filter(({ guid: itemGuid }) => itemGuid == guid ?? [])
}
function filterPoi(items) {
return items.poi?.filter(({ guid: itemGuid }) => itemGuid == guid ?? [])
}
function mapCoordinates(items) {
return items.map(({ coordinate }) => coordinate)
}
function flat(items) {
return items.flat();
}
return [filterPortals, filterPoi, mapCoordinates, flat].reduce((fn), Object.values(state.storeLayout.items))
}

这将返回所需的结果:

Object.values(state.storeLayout.items).flatMap((level) => {
let tmpLevel = {...level}
tmpLevel.portal = tmpLevel.portal?.filter((x) => (x.guid === guid) ?? []
tmpLevel.poi = tmpLevel.poi?.filter((x) => (x.guid === guid)) ?? []
return tmpLevel.poi.concat(tmpLevel.portals)
} ?? []).map((poi) => poi.coordinate)

感谢大家阅读并发布答案来帮助我!

最新更新