0

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
  }
]
Caio Kawasaki
  • 2,894
  • 6
  • 33
  • 69
  • Assuming `a` and `b` are your arrays, with plain JS -> `a.filter(x => !b.find(k => k.conversation_id === x.id))` – Keith Jan 16 '19 at 14:30

4 Answers4

1

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>
Avanthika
  • 3,984
  • 1
  • 12
  • 19
1

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)
Alexandre Elshobokshy
  • 10,720
  • 6
  • 27
  • 57
1

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) 
Jomoos
  • 12,823
  • 10
  • 55
  • 92
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>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209