Compare two arrays of objects and remove items in the second one that have the same property value

后端 未结 8 788
温柔的废话
温柔的废话 2020-12-06 01:55

All I need to do is compare two arrays of objects and remove items in the second one that have the same property value. For example:

var a = [{\'name\':\'bob         


        
8条回答
  •  感情败类
    2020-12-06 02:06

    let A = [
      {name: 'a', age: 20},
      {name: 'b', age: 30},
      {name: 'c', age: 10},
    ]
    
    let B = [
      {name: 'a', age: 20},
      {name: 'b', age: 40},
      {name: 'd', age: 10},
      {name: 'e', age: 20},
      {name: 'f', age: 10},
    ]
    
    const compareName = (obj1, obj2)=>{
      return (obj1.name === obj2.name);
    }
    
    const compareAll = (obj1, obj2)=>{
      return (obj1.name === obj2.name && obj1.age=== obj2.age);
    }
    
    let output = B.filter(b=>{
      let indexFound = A.findIndex(a => compareName(a, b));
      return indexFound == -1;
    })
    

    Depending on which Objects you want to remove use:

    1. compareName : Remove objects which have common name
    2. compareAll : Remove objects which have both name & age common

    Also to find common Objects list just add use return index != -1

    PS: Refer my Github for Array Data Manipulation examples in Javascript

提交回复
热议问题