[removed] Merge Two Arrays of Objects, Only If Not Duplicate (Based on Specified Object Key)

前端 未结 3 665
情书的邮戳
情书的邮戳 2020-12-20 11:48

Background

Say I have an initial array of objects:

var initialData = [
    {
        \'ID\': 1,
        \'FirstName\': \'Sally\'
    },
    {
              


        
3条回答
  •  自闭症患者
    2020-12-20 12:35

    You can create a set of IDs from initialData and this will make "check if ID is already in initial data" faster - O(1):

    var initialData = [{
        'ID': 1,
        'FirstName': 'Sally'
      },
      {
        'ID': 2,
        'FirstName': 'Jim'
      },
      {
        'ID': 3,
        'FirstName': 'Bob'
      }
    ];
    
    var newData = [{
        'ID': 2,
        'FirstName': 'Jim'
      },
      {
        'ID': 4,
        'FirstName': 'Tom'
      },
      {
        'ID': 5,
        'FirstName': 'George'
      }
    ];
    
    var ids = new Set(initialData.map(d => d.ID));
    var merged = [...initialData, ...newData.filter(d => !ids.has(d.ID))];
    
    console.log(merged);

    The final runtime of this approach is O(n + m).

    If you want to be slightly more efficient, you can consider looping through newData and pushing any new elements to the final result array manually (instead of using filter and the spread operator).

提交回复
热议问题