根据 Ramda 中数组中的值过滤集合 [英] Filter collection based on values in array in Ramda

查看:28
本文介绍了根据 Ramda 中数组中的值过滤集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组唯一值:

const 数组 = [1, 2, 4]

我有一组独特的对象:

const 集合 = [{类型:1,眼睛:'蓝色'},{类型:2,眼睛:'棕色'},{类型:3,眼睛:'绿色'},{类型:4,眼睛:'蓝色'}]

使用 Ramda 如何从 collection 中提取类型包含在 array 中的所有对象?

预期结果:

<预><代码>[{类型:1,眼睛:'蓝色'},{类型:2,眼睛:'棕色'},{类型:4,眼睛:'蓝色'}]

解决方案

使用 R.innerJoin():

const array = [1, 2, 4]const collection = [{ 类型:1,眼睛:'蓝色'},{ 类型:2,眼睛:'棕色'},{ 类型:3,眼睛:'绿色'},{ 类型:4,眼睛:'蓝色'}]const joinByType = R.innerJoin((o, 类型) =>o.type === 类型)const 结果 = joinByType(集合,数组)console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

使用 R.propEq()type 属性与数组中的类型 ID 进行比较.我们需要使用 R.flip() 因为innerJoin 传递对象在要比较的值之前.

const array = [1, 2, 4]const collection = [{ 类型:1,眼睛:'蓝色'},{ 类型:2,眼睛:'棕色'},{ 类型:3,眼睛:'绿色'},{ 类型:4,眼睛:'蓝色'}]const joinByType = R.innerJoin(R.flip(R.propEq('type')))const 结果 = joinByType(集合,数组)console.log(result)

<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

I have an array of unique values:

const array = [1, 2, 4]

I have a collection of unique objects:

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

Using Ramda how do I extract all the objects from collection where type is included in array?

Expected outcome:

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

解决方案

Use 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>

The same method in a more ramdaish way using R.propEq() to compare the type property with the type id from the array. We need to use R.flip() because innerJoin passes the object before the the value to compare to.

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>

这篇关于根据 Ramda 中数组中的值过滤集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆