Asim K T
Asim K T

Reputation: 18144

Ramda: get objects from array by comparing with each item in another array

I've an array like:

ids = [1,3,5];

and another array like:

items: [
{id: 1, name: 'a'}, 
{id: 2, name: 'b'}, 
{id: 3, name: 'c'}, 
{id: 4, name: 'd'}, 
{id: 5, name: 'e'}, 
{id: 6, name: 'f'}
];

What I want is another array like:

array = [{id: 1, name: 'a'}, {id: 3, name: 'c'}, {id: 5, name: 'e'}];

I can't get my head around it. so far i tried like:

console.log(R.filter(R.propEq('id', <donnow what shud be here>), items);
console.log( R.pick(ids)(items))

Upvotes: 2

Views: 4789

Answers (4)

cstuncsik
cstuncsik

Reputation: 2786

If you still want to do with Ramda:

const ids = [1,3,5];

const items = [
{id: 1, name: 'a'}, 
{id: 2, name: 'b'}, 
{id: 3, name: 'c'}, 
{id: 4, name: 'd'}, 
{id: 5, name: 'e'}, 
{id: 6, name: 'f'}
];

console.log(

  R.filter(R.compose(R.flip(R.contains)(ids), R.prop('id')), items)

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

Upvotes: 5

Jagdish Idhate
Jagdish Idhate

Reputation: 7742

Or may be one liner without Ramda

items.filter(x=>ids.includes(x.id))

Upvotes: 4

Nina Scholz
Nina Scholz

Reputation: 386578

I suggest to use a hash table for faster lookup.

var ids = [1, 3, 5],
    items = [{id: 1, name: 'a'}, {id: 2, name: 'b'}, {id: 3, name: 'c'}, {id: 4, name: 'd'}, {id: 5, name: 'e'}, {id: 6, name: 'f'} ],
    filtered = items.filter(function(obj) {
        return this[obj.id];
    }, ids.reduce(function (r, a) {
        r[a] = true;
        return r;
    }, Object.create(null)));

document.write('<pre>' + JSON.stringify(filtered, 0, 4) + '</pre>');

Upvotes: 1

Andreas Louv
Andreas Louv

Reputation: 47099

You can use .filter and .indexOf. Note these are ECMA5 methods for Arrays, and will not work in IE8.

var ids = [1, 3, 5];
var items = [
  {id: 1, name: 'a'}, 
  {id: 2, name: 'b'}, 
  {id: 3, name: 'c'}, 
  {id: 4, name: 'd'}, 
  {id: 5, name: 'e'}, 
  {id: 6, name: 'f'}
];

var filtered = items.filter(function(obj) {
  return ids.indexOf(obj.id) > -1;
});
console.log(filtered); // [{id: 1, name: 'a'}, {id: 3, name: 'c'}, {id: 5, name: 'e'}];

Upvotes: 4

Related Questions