Sign in
Log inSign up

Practice Problem 3: Union

miguelmanalo's photo
miguelmanalo
·Jun 22, 2020

This one was fun too! A slight twist on the intersection problem. I couldn't rely on the object doing all the work for me. But it could still do half the work.

/* 
Problem 3: Union

Construct a function union that takes an input array of arrays, compares each array, and returns a new flat array that contains all elements. If there are duplicate elements, only add it once to the new array. Preserve the order of the elements starting from the first element of the first input array.
*/

const a1 = [5, 10, 15];
const a2 = [15, 88, 1, 5, 7];
const a3 = [100];
console.log(union([a1, a2, a3])); // should log: [5, 10, 15, 88, 1, 7, 100]

//make a function named union and have it take an array of arrays
//look at each array and make one new array out of all of them
//in the new array have each unique item only once
//also preserve the given ordering of the items

function union(arr) {
  //make a new mega array and object called objHolder
  let megaArray = [];
  const objHolder = {};
  //iterate through each array with for...of
  for (let item of a1) {
    //if the key value pair doesn't exist make it and also push the value to the megaArray since this is the first time we see the item
    //if it sees a duplicate number, the push doesn't happen because the value is 1 and no longer undefined
    if (objHolder[item] === undefined) {
      objHolder[item] = 1;
      megaArray.push(item);
    }
  }
  for (let item of a2) {
    if (objHolder[item] === undefined) {
      objHolder[item] = 1;
      megaArray.push(item);
    }
  }
  for (let item of a3) {
    if (objHolder[item] === undefined) {
      objHolder[item] = 1;
      megaArray.push(item);
    }
  }
  return megaArray;
}