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

前端 未结 4 1076
-上瘾入骨i
-上瘾入骨i 2021-01-03 13:40

I\'ve an array like:

ids = [1,3,5];

and another array like:

items: [
{id: 1, name: \'a\'}, 
{id: 2, name: \'b\'}, 
{id: 3,          


        
相关标签:
4条回答
  • 2021-01-03 14:12

    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'}];
    
    0 讨论(0)
  • 2021-01-03 14:14

    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>

    0 讨论(0)
  • 2021-01-03 14:16

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

    0 讨论(0)
  • 2021-01-03 14:19

    Or may be one liner without Ramda

    items.filter(x=>ids.includes(x.id))
    
    0 讨论(0)
提交回复
热议问题