JavaScript数组过滤和映射

时间:2020-08-03 13:55:51

标签: javascript arrays filter mapping

我一直在回答问题上没有回答一个明确的问题,因此,香港专业教育学院决定尝试从概念上推断我想做的事情,看看我是否无法获得关于如何进行回应的答案。 / p>

filters= ["Bill Johnson", "hasStartDocs"]
mappedArray = 
[
  {
  name:'Larry', 
  docs:{
   startDocs:[{...}]
   },
  workers:{
  sales:["Bill Johnson"]
  }  
]    

因此,如果filter [i]有空格{''},请检查worker下的所有数组是否包含filter [i]之类的字符串,然后进行映射 基于该条件的filteredMappedArray

如果filter [i]没有空格,请创建一个新字符串,将字符串的前3个字符切片,使该新字符串的首字母小写(thatString =“ startDocs”)eval(resoStatus。$ {thatString} .length> 0),然后像这样映射filteredMappedArray。

因此之后,对于[i]的每个实例,您将拥有一个唯一的映射。因此,如果有人单击5个过滤器,则每个过滤器都会有一个filteredMappedArray,如果它们具有相同的_id,我想您应该是.concat()和.reduce()。

我不需要有人来帮助进行字符串操作。我需要在正确的方向上轻推一下如何同时使用filter []和mappingArray []创建1个filteredMappedArray。请,谢谢。

for(i=0,i<filters.length,i++){
filters.map(filter => filter.includes(' ') //map mappedArray based on rules above)
filters.map(filter => filter.includes(/^has/ //map mappedArray based on rules above)
}

这给你

[filteredMappedArray1]
[filteredMappedArray2]

bigArray = filteredMappedArray1.concat(filteredMappedArray2)

smallArray = bigArray.forEach(map //if the map is unique delete it if the map isnt unique keep it but remove all the duplicates)

1 个答案:

答案 0 :(得分:1)

据我所知,您没有进行任何映射,只是对mappedArray进行过滤以将其限制为与filters中的至少一个过滤器匹配的条目。

如果是这样,请执行以下操作(请参阅注释),前提是您没有比mappedArray中的条目多得多的过滤器(如果您这样做,则结构会有所不同,但这似乎不太可能给我):

// The `length` check prevents filtering if there are no filters; that's usually how people
// implement filters, but remove it if that's not right in your case
const filteredArray = filters.length === 0 ? mappedArray : mappedArray.filter(entry => {
    // `some` returns `true` if the callback returns a truthy value (and
    // stops loopihng); it returns `false` if it reaches the end of the
    // array without the callback rturning a truthy value. So basically
    // this is saying "return true if any filter matches."
    return filters.some(filter => {
        if (filter.includes(" ")) {
            // Check `workers` arrays
            for (const array of Object.values(entry.workers)) {
                if (array.includes(filter)) {
                    return true;
                }
            }
        } else {
            // Check `docs` for at least one entry for the given type
            const key = /*...strip leading three, change case of fourth...*/;
            const array = entry.docs.key];
            if (array && array.length > 0) { // There's at least one entry
                return true;
            }
        }
        return false;
    });
});