2

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))
Asim K T
  • 16,864
  • 10
  • 77
  • 99

4 Answers4

5

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>
customcommander
  • 17,580
  • 5
  • 58
  • 84
cstuncsik
  • 2,698
  • 2
  • 16
  • 20
4

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'}];
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
4

Or may be one liner without Ramda

items.filter(x=>ids.includes(x.id))
Jagdish Idhate
  • 7,513
  • 9
  • 35
  • 51
1

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>');
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • This is quite useful when you have a large collection and/or when you want to curry the ids into a reusable function. I probably wouldn't accept the overhead of creating that temporary structure otherwise. – Scott Sauyet Sep 12 '19 at 13:06
  • Also, while I usually find your code quite easy to read, something about the indentation here seems off. `Object.create...` looks to be a third parameter to `filter`. – Scott Sauyet Sep 12 '19 at 13:09
  • you are right, the formatting is wrong, but today i wouls write it with a `Set` instead (as variable, not as `thisArg`). – Nina Scholz Sep 12 '19 at 13:12
  • Yes, I had somehow missed that this was an old post when it came to my attention today. Sorry about that. – Scott Sauyet Sep 12 '19 at 13:29