Asim K T Asim K T - 17 days ago 7
Javascript Question

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

Answer

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'}];
Comments