Home > Enterprise >  How to get the differences between two arrays in JavaScript, including moved items
How to get the differences between two arrays in JavaScript, including moved items

Time:10-07

I have two arrays, which represent two versions of the same array, and I would like to know the difference between them.

Unlike earlier questions, I would also like to know about items that merely moved. If an item is in both arrays, but it's in different places, I'd like to know about it. Additionally, I do not want items in the result diff that only moved because other items were added or removed, which of course causes all following items to change indices. I only consider items to have moved, if they changed their relative position to each other.

let old = [ "b", "c", "d", "e", "f", "g", "h", "i", "j" ];
let news = [ "a", "d", "c", "e", "f", "h", "i", "j" ];

// algo should result in
let added = [ "a" ];
let removed = [ "b", "g" ];
let moved = [ "d", "c" ];

CodePudding user response:

let old = [ "b", "c", "d", "e", "f", "g", "h", "i", "j" ];
let news = [ "a", "d", "c", "e", "f", "h", "i", "j" ];

let added = news.filter(item => !old.includes(item));
let removed = old.filter(item => !news.includes(item));
// find items that only changed place
let oldCommon = old.filter(item => news.includes(item));
let newCommon = news.filter(item => old.includes(item));
let moved = newCommon.filter((item, i) => item != oldCommon[i]);

CodePudding user response:

This solution also deals with duplicate problems.

let oldArray = [ "b", "c", "d", "e", "f", "g", "h", "i", "j" ];
let newArray = [ "a", "d", "c", "e", "f", "h", "i", "j" ];

let added = newArray.filter(function(item) {
  return oldArray.indexOf(item) === -1;
});
let removed = oldArray.filter(function(item) {
  return newArray.indexOf(item) === -1;
});
let moved = newArray.filter(function(item) {
  return oldArray.indexOf(item) !== -1 && newArray.indexOf(item) !== -1 && oldArray.indexOf(item) !== newArray.indexOf(item);
});
console.log(added);
console.log(removed);
console.log(moved);

  • Related