How to find new and deleted items between two JavaScript arrays

I have two arrays filled with objects and I need to determine which items have been added and which ones have been removed when I compare the two.

var originalList = [{
  userId: 101,
  product: "Laptop"
}, {
  userId: 102,
  product: "Phone"
}, {
  userId: 103,
  product: "Tablet"
}];

var updatedList = [{
  userId: 101,
  product: "Laptop"
}, {
  userId: 103,
  product: "Tablet"
}, {
  userId: 104,
  product: "Monitor"
}];

What I am looking to achieve is:

  • New items: [{ userId: 104, product: "Monitor" }]
  • Removed items: [{ userId: 102, product: "Phone" }]

I attempted to use a few array methods but my solution became quite messy and difficult to follow. I’m in search of a more concise way to do this comparison.

I hit this exact problem building a shopping cart feature. Here’s what worked best for me - using Map objects for better performance, especially with larger datasets. Convert both arrays to Maps using userId as the key, then iterate through to find differences.

const originalMap = new Map(originalList.map(item => [item.userId, item]));
const updatedMap = new Map(updatedList.map(item => [item.userId, item]));

const newItems = updatedList.filter(item => !originalMap.has(item.userId));
const removedItems = originalList.filter(item => !updatedMap.has(item.userId));

This scales way better than nested loops since Map.has() is O(1) vs O(n) with some(). Saw huge performance gains with arrays of thousands of objects. Code stays clean and runs much faster than filter/some combos.

use filter() and some() to find new items: const newItems = updatedList.filter(updated => !originalList.some(orig => orig.userId === updated.userId)). for removed items, just reverse it. it’s a pretty clean way to compare objects.

I’ve had good luck with Set operations for cleaner comparison logic. Build sets of the unique IDs first, then use math difference:

const originalIds = new Set(originalList.map(item => item.userId));
const updatedIds = new Set(updatedList.map(item => item.userId));

const newItems = updatedList.filter(item => !originalIds.has(item.userId));
const removedItems = originalList.filter(item => !updatedIds.has(item.userId));

This works great when you only care about adds and deletes, not changes. Set lookups are fast and the code reads like plain English. Way easier to debug than some() since you can check the Sets separately.

This topic was automatically closed 6 hours after the last reply. New replies are no longer allowed.