Lodash - DifferenceBy with different identity

无人久伴 提交于 2019-12-13 03:45:32

问题


I have the following array:

[
  {
    id: 1
  },
  {
    id: 2
  },
  {
    id: 3
  },
  {
    id: 4
  }
]

Every 5 seconds my application receives a new array and I need to compare the difference between the next one...

So the next array is:

[
  {
    conversation_id: 1
  },
  {
    conversation_id: 2
  },
  {
    conversation_id: 4
  }
]

Considering that identity is different. How can I compare with the previous and get an array with the excluded item?

[
  {
    id: 3
  }
]

回答1:


Use _.differenceWith():

const prev = [{"id":1},{"id":2},{"id":3},{"id":4}]
const next = [{"conversation_id":1},{"conversation_id":2},{"conversation_id":4}]

const diff = _.differenceWith(prev, next, ({ id }, { conversation_id }) => _.eq(id, conversation_id))
console.log(diff)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.js"></script>



回答2:


I think you can use mix of javascript and lodash to solve this problem.

var arrayList = [
  {
    id: 1
  },
  {
    id: 2
  },
  {
    id: 3
  },
  {
    id: 4
  }
];

var conv_array = [
  {
    conversation_id: 1
  },
  {
    conversation_id: 2
  },
  {
    conversation_id: 4
  }
];

var itemsNotInArray = [];

arrayList.filter(function (item) {
    if (!_.find(conv_array, {conversation_id: item.id })) {
      console.log("not in array", item);
      itemsNotInArray.push(item);
    }
});
console.log("result you expected", itemsNotInArray);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>



回答3:


Filter the first array and compare each value till you find a missing id :

var array1 = [{
    id: 1
  },
  {
    id: 2
  },
  {
    id: 3
  },
  {
    id: 4
  }
];

var array2 = [{
    conversation_id: 1
  },
  {
    conversation_id: 2
  },
  {
    conversation_id: 4
  }
];

var test = array1.filter(
    conv => !array2.find(
          id => id.conversation_id === conv.id
       )
    );
console.log(test)



回答4:


From lodash documentation, the third argument to differenceBy is

[iteratee=_.identity] (Function): The iteratee invoked per element.

Based on this, you can use

var current = [
    {
        id: 1
    },
    {
        id: 2
    },
    {
        id: 3
    },
    {
        id: 4
    }
];

and

var next = [
    {
        conversation_id: 1
    },
    {
        conversation_id: 2
    },
    {
        conversation_id: 4
    }
];

then

var difference = _.differenceBy(current, next, function(obj) {
    return obj.id || obj.conversation_id;
});

Or shortened with an arrow function:

var difference = _.differenceBy(current, next, (x) => x.id || x.conversation_id) 


来源:https://stackoverflow.com/questions/54219162/lodash-differenceby-with-different-identity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!