hyprstack
hyprstack

Reputation: 4228

Ramda - find objects that match from arrays

From the two following lists list1 and list2, I need to return the objects from list1 that match the values of head and tail from list2.

I was trying to achieve this using 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

Upvotes: 1

Views: 1847

Answers (2)

kakamg0
kakamg0

Reputation: 1096

If you want to use ramdajs you can use innerJoin to select the items that match a predicate like this:

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>

Upvotes: 4

Giang Le
Giang Le

Reputation: 7044

Yeah.

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

Find will return the first match. If you want to find all match. Change find to filter

Upvotes: 1

Related Questions