2

I'm stuck with this problem for 3 days now... Someone please help me.

Challenge 5
Construct a function intersection that compares input arrays and returns a new array with elements found in all of the inputs.

function intersection(arrayOfArrays) {

}

console.log(intersection([[5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]]));

// should log: [5, 15]
0

6 Answers 6

4

Reduce the arrays to a Map of counts, with the value as key. Spread the Map to entries. Use Array.filter() on the Map's entries to remove all entries, which value is not equal to the arrayOfArrays lenth. Extract the original number from the entries using Array.map():

function intersection(arrayOfArrays) {
  return [...arrayOfArrays.reduce((r, s) => {
    s.forEach((n) => r.set(n, (r.get(n) || 0) + 1));
    
    return r;
  }, new Map())]
  .filter(([k, v]) => v === arrayOfArrays.length)
  .map(([k]) => k);
}

console.log(intersection([[5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]]));

Sign up to request clarification or add additional context in comments.

2 Comments

Something tells me that will only confuse OP more.
yeah it took me awhile to learn =>, reduce, and spread&rest operator lol
3

You could reduce the array by filtering with just checking if the other array contains the value.

This works for arrays with unique values.

Array#reduce:

If no initialValue is provided, then accumulator will be equal to the first value in the array, and currentValue will be equal to the second.

The callback

a.filter(v => b.includes(v))

filters array a. If the array b includes the value of a, then this value v is included in the accumulator for the next iteration or as final result.

     accumulator            currentValue           new accumulator
          a                       b                    result
--------------------    --------------------    --------------------
[     5, 10, 15, 20]    [15, 88,  1,  5,  7]    [             5, 15]
[             5, 15]    [ 1, 10, 15,  5, 20]    [             5, 15]

function intersection(arrayOfArrays) {
    return arrayOfArrays.reduce((a, b) => a.filter(v => b.includes(v)));
}

console.log(intersection([[5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]]));

1 Comment

Hi Nina, I'm a beginner and trying to figure out how your code works. Is it possible to explain more details about how reduce((a, b) => a.filter()) work?
0

First try to find out the intersection of two arrays which is the base problem. Then try to build up for variable number of arrays passed as arguments for intersection. You can use reduce() for doing that.

function intersectionOfTwoArrays(arr1, arr2)
{
   return arr1.filter(x => arr2.some(y => y === x)); 
}


function intersection(...arrayOfArrays)
{
	return arrayOfArrays
	       .reduce((a, b) => intersectionOfTwoArrays(a, b));
}

intersection(
[5, 10, 15, 20], 
[15, 88, 1, 5, 7], 
[1, 10, 15, 5, 20]
);

Comments

0

You can go through the first array in the array of arrays and check which of its value is present in all the other arrays.

Here is an example:

function intersection(input) {
    let firstArray = input[0];
    let restOfArrays = input.splice(1);
    return firstArray.filter(v => restOfArrays.every(arr => arr.includes(v)));    
}

const input = [[5, 10, 15, 20], [15, 88, 1, 5, 7], [1, 10, 15, 5, 20]];
const result = intersection(input);

console.log(result);

Comments

0

Works with even if there is duplicate in same array.. like in my example added 5 twice in arrayEle[1];

var arrayEle = [[5, 10, 15, 20], [15, 88, 1, 5, 5], [1, 10, 15, 5, 20]]
var startIndex = 1;
var newArray = [];
for (var x = 0; x < arrayEle[0].length; x++) {
  var temVal = 1;
  var value;
  for (var y = 1; y < arrayEle.length; y++) {
    for (var z = 0; z < arrayEle[y].length; z++) {
      if (arrayEle[y][z] == arrayEle[0][x]) {
        temVal++;
        value = arrayEle[y][z];
        break;
      }
    }
  }
  if (temVal == arrayEle.length) {
    newArray.push(value);
    console.log(value);
  }
}
console.log(newArray);


//log: [5, 15]

Comments

0

I think you want the common elements. Let me show you how:

var Array1 = [5, 10, 15, 20]
var Array2 = [15, 88, 1, 5, 7]
var Array3 = [1, 10, 15, 5, 20]
var found = []
var Final = []
var c = 1;e = 1;
for (i = 1;i<=Array1.length;i++){
    for (k = 1;k<=Array2.length;i++){
        if (Array1[i] == Array2[k]){
            Found[c] = Array[i];
            c++;
        }
    }
}
for (n = 1;n <= Found.length ; n++){
    for (m = 1;m <= Array3.length ; n++){
        if (Found[n] == Array3[m]){
            Final[e] = Found[n]
            e++; 
        }
    }
}
//the Array Final Contains 5 , 15

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.