0

I would like to create an algorithm (or use an existing js library/fn) that would merge two arrays together so that

  • values are dropped from the results that are not in the replacing array compared to original
  • value is added if not exist in the original array
  • duplicates are not added
  • Arrays do not have to be the same size

E.g.

const originalArray = [1,2,3];
const replacingArray = [1,5,3,4]; // 2 is missing and 5,4 are new compared to the original

const result = merge(originalArray, replacingArray); 

console.log(result) // [1,5,3,4]

How could I achieve that? What would be the merge function?

anmatika
  • 1,581
  • 3
  • 21
  • 29

2 Answers2

1
const originalArray = [1,2,3];
const replacingArray = [1,5,3,4];

const result = [...replacingArray];

The combination of those rules is effectively the same as replacing the original array with the replacement array.

If you need the results to end up in originalArray:

const originalArray = [1,2,3];
const replacingArray = [1,5,3,4];

originalArray.splice(0, originalArray.length, ...replacingArray);
Ouroborus
  • 16,237
  • 4
  • 39
  • 62
0

If we apply the specified rules, then we don't have to do anything complex, we can just assign the replacingArray to the result array. Result will be the same if you do this or use some complex fn or algorithm.

const originalArray = [1,2,3];
const replacingArray = [1,5,3,4]; 

const result = replacingArray;

console.log(result); // [1,5,3,4]
  • If altering a variable, you should use `let` instead of `const` https://stackoverflow.com/a/31900705/15291770 – Harrison Jul 24 '23 at 10:35
  • Hey Harrison, Thank you for your comment and that link is help full But we aren't reassigning the value , we are assigning it to another variable. – Killers playground Jul 25 '23 at 03:57