Remove array of objects from another array of objects

前端 未结 4 1879
情话喂你
情话喂你 2021-02-06 11:17

Assume we have the following arrays of objects to be compared based on property id:

a = [{\'id\':\'1\', \'name\':\'a1\'}, {\'id\':\'2\', \'name\':\'         


        
4条回答
  •  我在风中等你
    2021-02-06 12:00

    Here is a nice one line answer :)

    Basically, you can filter, as you were trying to do already. Then you can also filter b for each a element and if the length of the filtered b is zero, then you return true because that means the a element is unique to a.

    var a = [{
      'id': '1',
      'name': 'a1'
    }, {
      'id': '2',
      'name': 'a2'
    }, {
      'id': '3',
      'name': 'a3'
    }];
    
    var b = [{
      'id': '2',
      'name': 'a2'
    }];
    
    c = a.filter( x => !b.filter( y => y.id === x.id).length);
    console.log(c);

提交回复
热议问题