簡體   English   中英

根據Ramda中數組中的值過濾收集

[英]Filter collection based on values in array in Ramda

我有一個唯一值數組:

const array = [1, 2, 4]

我有一個獨特的對象集合:

const collection = [
  { type: 1, eyes: 'blue'},
  { type: 2, eyes: 'brown'},
  { type: 3, eyes: 'green'},
  { type: 4, eyes: 'blue'}
]

使用Ramda,如何從collection中提取array包含類型的所有對象?

預期結果:

[
  { type: 1, eyes: 'blue'},
  { type: 2, eyes: 'brown'},
  { type: 4, eyes: 'blue'}
]

使用R.innerJoin()

 const array = [1, 2, 4] const collection = [{ type: 1, eyes: 'blue'},{ type: 2, eyes: 'brown'}, { type: 3, eyes: 'green'}, { type: 4, eyes: 'blue'}] const joinByType = R.innerJoin( (o, type) => o.type === type ) const result = joinByType(collection, array) console.log(result) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script> 

使用R.propEq()type屬性與數組中的type id進行比較,以相同的方式進行比較。 我們需要使用R.flip()因為innerJoin在要比較的值之前傳遞了對象。

 const array = [1, 2, 4] const collection = [{ type: 1, eyes: 'blue'},{ type: 2, eyes: 'brown'}, { type: 3, eyes: 'green'}, { type: 4, eyes: 'blue'}] const joinByType = R.innerJoin(R.flip(R.propEq('type'))) const result = joinByType(collection, array) console.log(result) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script> 

沒有拉姆達

collection.filter(item => array.includes(item.type))

我認為Mukesh Soni的答案就是您需要的。 在Ramda中,它可能會讀取filter(p => array.includes(p.type), collection) ,但這幾乎是相同的。

但是Ramda只是關於函數 ,並且創建可重用和靈活的函數來滿足您的需求。 我至少會考慮編寫如下內容:

 const {curry, filter, contains, prop} = R const collection = [{ type: 1, eyes: 'blue'},{ type: 2, eyes: 'brown'}, { type: 3, eyes: 'green'}, { type: 4, eyes: 'blue'}] const array = [1, 2, 4] const filterBy = curry((propName, selectedValues, collection) => filter(e => contains(prop(propName, e), selectedValues), collection)) const newCollection = filterBy('type', array, collection) console.log(newCollection) 
 <script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.js"></script> 

我什至可以更進一步,並允許使用任意轉換函數,而不僅僅是prop

const filterBy = curry((transform, selectedValues, collection) => 
  filter(e => selectedValues.includes(transform(e)), collection))

filterBy(prop('type'), array, collection)

但是,此類抽象通常僅在希望在整個應用程序中使用它們的情況下才有用。 如果這是唯一使用值列表進行匹配以過濾集合的地方,則沒有理由使用任何可重用的函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM