Ramda - 从数组中查找匹配的对象

Ramda - find objects that match from arrays

从以下两个列表 list1list2 中,我需要 return 来自 list1 的对象与 headtail 来自 list2.

我试图使用 ramdajs 来实现这一点。

const list1 = [ 
  { tail: 'A', head: 'B', distance: '5' },
  { tail: 'B', head: 'C', distance: '4' },
  { tail: 'C', head: 'D', distance: '8' },
  { tail: 'D', head: 'C', distance: '8' },
  { tail: 'D', head: 'E', distance: '6' },
  { tail: 'A', head: 'D', distance: '5' },
  { tail: 'C', head: 'E', distance: '2' },
  { tail: 'E', head: 'B', distance: '3' },
  { tail: 'A', head: 'E', distance: '7' } 
]

const list2 = [ { tail: 'A', head: 'B' }, { tail: 'B', head: 'C' } ]

// result should be [{ tail: 'A', head: 'B', distance: '5' },
// { tail: 'B', head: 'C', distance: '4' }] from list1

是的。

const list = list1.find(item => {
     return list2.findIndex(i => i.head === item.head && i.tail === item.tail) !== -1;
});

查找将 return 第一个匹配项。如果你想找到所有匹配项。将 find 更改为 filter

如果您想使用 ramdajs,您可以使用 innerJoin 来 select 匹配谓词的项目,如下所示:

const list1 = [ 
  { tail: 'A', head: 'B', distance: '5' },
  { tail: 'B', head: 'C', distance: '4' },
  { tail: 'C', head: 'D', distance: '8' },
  { tail: 'D', head: 'C', distance: '8' },
  { tail: 'D', head: 'E', distance: '6' },
  { tail: 'A', head: 'D', distance: '5' },
  { tail: 'C', head: 'E', distance: '2' },
  { tail: 'E', head: 'B', distance: '3' },
  { tail: 'A', head: 'E', distance: '7' } 
];

const list2 = [ { tail: 'A', head: 'B' }, { tail: 'B', head: 'C' } ];

const result = R.innerJoin(
  (item1, item2) => item1.tail === item2.tail && item1.head === item2.head,
  list1,
  list2
);

console.log(result);
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>