Ramda: get objects from array by comparing with ea

2020-02-29 11:43发布

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

4条回答
我只想做你的唯一
2楼-- · 2020-02-29 12:22

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>

查看更多
何必那么认真
3楼-- · 2020-02-29 12:29

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'}];
查看更多
做个烂人
4楼-- · 2020-02-29 12:31

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

查看更多
对你真心纯属浪费
5楼-- · 2020-02-29 12:32

Or may be one liner without Ramda

items.filter(x=>ids.includes(x.id))
查看更多
登录 后发表回答