Tuesday, 4 April 2017

How to get the difference between two arrays but keeping repeat objects

Lets say that you have two arrays with objects, Array 1 and Array 2. The issue I am having is finding the exact difference between the two arrays, which may include elements that are seemingly equal to each. In this example, I commented the specific objects in each array.

Think of this in terms of having a shopping cart with repeat items, but you can only redeem one item. So //number 4 is one of the repeat items, but you still need it in Array 3


ARRAY 1

[
  { // number 1
    item_id: 4,
    total_price: 2.71
  },
  { // number 2
    item_id: 2,
    total_price: 3.71
  },
  { // number 3
    item_id: 4,
    total_price: 1.71
  },
  { // number 4
    item_id: 4,
    total_price: 2.71
  }
]


ARRAY 2

[
  { // number 1
    item_id: 4,
    total_price: 2.71
  }
]

How do I find the difference between these two arrays, Array 3?? And would it be best to have a unique key on each object to compare easier? Doing this in javascript/node and mainly using lodash.

ARRAY 3

[
  { // number 2
    item_id: 2,
    total_price: 3.71
  },
  { // number 3
    item_id: 4,
    total_price: 1.71
  },
  { // number 4
    item_id: 4,
    total_price: 2.71
  }
]



via Thomas Gorczynski

No comments:

Post a Comment