skip to Main Content

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?

2

Answers


  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);
    
    Login or Signup to reply.
  2. 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]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search