Lodash-不同身份的人

时间:2019-01-16 14:24:33

标签: javascript lodash

我有以下数组:

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

我的应用程序每隔5秒就会收到一个新数组,我需要比较下一个数组之间的差异...

所以下一个数组是:

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

考虑到身份是不同的。如何与前一个比较并获得包含排除项的数组?

[
  {
    id: 3
  }
]

4 个答案:

答案 0 :(得分:1)

我认为您可以混合使用javascript和lodash来解决此问题。

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>

答案 1 :(得分:1)

过滤第一个数组并比较每个值,直到找到缺少的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)

答案 2 :(得分:1)

lodash documentation中,differenceBy的第三个参数是

  

[iteratee=_.identity] (Function):每个元素调用的迭代器。

基于此,您可以使用

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

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

然后

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

或通过箭头功能缩短:

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

答案 3 :(得分:1)

使用_.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>