Sign in
Log inSign up

Practice: Intersection - comparing multiple arrays

miguelmanalo's photo
miguelmanalo
·Jun 22, 2020

This was fun!

I finally sorta get how for...in and for...of work. For in is for objects and for...of is for arrays.

What I don't know is how to do this for an unknown number of arrays. The way I wrote it works just for three arrays named as they are and are placed inside another array.

Problem 2: Intersection Construct a function intersection that compares input arrays and returns a new array with elements found in all of the inputs.

//below was given
const arr1 = [5, 10, 15, 20];
const arr2 = [15, 88, 1, 5, 7];
const arr3 = [1, 10, 15, 5, 20];
intersection([arr1, arr2, arr3]); // should log: [5, 15]

//task: take all the arrays together and compare them
//you want to return a brand new array only with common elements from the given array
  //return brandNew Array = [onlyCommonNums]

//use for...of to iterate through each array
//and put everything into an object and count
//then anything with a key:value pair of 3 gets pushed to my result array
//can use for...in to iterate through the object
//and find the needed value

function intersection(arr) {
  //create the empty object to hold my count
  const holdingObj = {};
  //create array to put result into
  const resultArray = [];
  //use for...of to iterate thru each array since they're of diff lengths
  for (let item of arr1) {
    //if the key value pair doesn't exist make it and set it to 1
    if (holdingObj[item] === undefined) {
      holdingObj[item] = 1;
    //if the pair does exist increase by 1  
    } else if (holdingObj[item] !== undefined) {
      holdingObj[item] += 1;
    }
  }
  for (let item of arr2) {
    if (holdingObj[item] === undefined) {
      holdingObj[item] = 1;
    } else if (holdingObj[item] !== undefined) {
      holdingObj[item] += 1;
    }
  }
  for (let item of arr3) {
    if (holdingObj[item] === undefined) {
      holdingObj[item] = 1;
    } else if (holdingObj[item] !== undefined) {
      holdingObj[item] += 1;
    }
  }
  //now go through the object and pull out the keys with a value of 3
  for (const key in holdingObj) {
    if (holdingObj[key] === 3) {
      //keys are in strings so we have to turn it back into a number
      resultArray.push(Number(key));
    }
  }
  return resultArray;
}