Jamie Hutber
Jamie Hutber

Reputation: 28074

Multi-Select Input - Find added and remove items Javascript

I have 2 data sets new and old. Old is the fields input before editing, new is the updated list.

I need to delete removed entries I need to add new entries

Old

[
    {"title":"40k","value":1},
    {"title":"Fantasy","value":2},
    {"title":"Space Hulk","value":4}
]

New

[
    {"title":"40k","value":1},
    {"title":"Fantasy","value":2},
    {"title":"Age of Sigma","value":3}
]

This is how the returned data should look:

[{"title":"Age of Sigma","value":3}] //Save Data
[{"title":"Space Hulk","value":4}]   //Delete Data

I had used to find the deleted items, but when I did this there were only 2 entries in the database. I blame the 3 month baby for brain fog!

export const findRemovedItems = (newData, oldData) =>
   oldData.filter(item => newData.map(checkItem => item.value !== checkItem.value).includes(true))

Upvotes: 0

Views: 30

Answers (2)

Ori Drori
Ori Drori

Reputation: 191976

Create a Set of the unique objects' (title in your case) property for each array. Use the Set to of old to filter new, and vice versa:

const getSetByKey = (arr, key) => new Set(arr.map(o => o[key]));
const filterBySet = (arr, set, key) => arr.filter(o => !set.has(o[key]));

const fn = (a, b, key) => {
  const aMap = getSetByKey(a, key);
  const bMap = getSetByKey(b, key);

  return {
    save: filterBySet(b, aMap, key),
    remove: filterBySet(a, bMap, key),
  };
};

const oldArr = [
  {"title":"40k","value":1},
  {"title":"Fantasy","value":2},
  {"title":"Space Hulk","value":4}
]
const NewArr = [
  {"title":"40k","value":1},
  {"title":"Fantasy","value":2},
  {"title":"Age of Sigma","value":3}
]

const result = fn(oldArr, NewArr, 'title');

console.log(result);

Upvotes: 0

Max
Max

Reputation: 4739

oldData.filter(i => !newData.some(j => j.value=== i.value))

Upvotes: 1

Related Questions