Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Diffing 2 arrays, i.e which items to add and remove

Tags:

javascript

Given:

  • array of "current" objects [{id: '1'},{id: '2'},{id: '3'},{id: '4'},{id: '5'}]
  • array of "new" objects [{id: '1'},{id: '5'},{id: '6'},{id: '7'},{id: '8'}]

How to determine which objects

  • to add (not in "current") and
  • to remove (not in "new")?

In this case:

  • {id: '2'},{id: '3'},{id: '4'} should be removed
  • {id: '6'},{id: '7'},{id: '8'} should be added

Performance is not extremely important, my dataset is usually around 200.

Edit: I need to know about elements to be added/removed because "current" array correlates to DOM nodes and I don't just want to delete them all and add from scratch - already tried that and performance is far from perfect.

like image 350
Solo Avatar asked Dec 28 '25 04:12

Solo


1 Answers

In both cases, this is a classic use case of the set operation "difference". All you need to do is define a difference function, and then apply it with current.difference(new) and new.difference(current).

function difference(a, b, compare) {
  let diff = [];
  for (let ai = 0; ai < a.length; ai++) {
    let exists = false;
    for (let bi = 0; bi < b.length; bi++) {
      if (compare(a[ai], b[bi])) {
        exists = true;
        break;
      }
    }
    if (!exists) diff.push(a[ai]);
  }

  return diff;
}

function getRemoved(oldA, newA) {
  return difference(oldA, newA, (a, b) => a.id == b.id);
}

function getAdded(oldA, newA) {
  return difference(newA, oldA, (a, b) => a.id == b.id);
}

let current = [{id: '1'}, {id: '2'}, {id: '3'}, {id: '4'}, {id: '5'}];
let newArr = [{id: '1'}, {id: '5'}, {id: '6'}, {id: '7'}, {id: '8'}];

console.log(getRemoved(current, newArr));
console.log(getAdded(current, newArr));
like image 174
Abion47 Avatar answered Dec 30 '25 19:12

Abion47