0

I have the following code below:

const intersection = (arr) => {

  //console.log(arr)

  return arr.reduce((a,e) => a+e, [])

}

const arr1 = [5, 10, 15, 20];
const arr2 = [15, 88, 1, 5, 7];
const arr3 = [1, 10, 15, 5, 20];
console.log(intersection([arr1, arr2, arr3]));

I am expecting my code to print [5,10,15,2015,88,1,5,71,10,15,5,20] but instead it's printing 5,10,15,2015,88,1,5,71,10,15,5,20

What am I doing wrong?

1
  • 1
    You're trying to apply the + operator to arrays, which javascript doesn't support. Use concat instead: (a,e) => a.concat(e) Commented Jun 8, 2019 at 21:55

2 Answers 2

1

You are trying to combine the arrays with the + operator. Since arrays don't support the + operator, they are casted to strings. You can use array spread or Array.concat() to combine them using Array.reduce():

const intersection = arr => arr.reduce((a, e) => [...a, ...e], [])

const arr1 = [5, 10, 15, 20];
const arr2 = [15, 88, 1, 5, 7];
const arr3 = [1, 10, 15, 5, 20];
console.log(intersection([arr1, arr2, arr3]));

Or you can use Array.flat():

const intersection = arr => arr.flat();

const arr1 = [5, 10, 15, 20];
const arr2 = [15, 88, 1, 5, 7];
const arr3 = [1, 10, 15, 5, 20];
console.log(intersection([arr1, arr2, arr3]));

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

Comments

0

Don't use + to add arrays. Use concat instead:

const intersection = arr => arr.reduce((a, e) => a.concat(e), []);

const arr1 = [5, 10, 15, 20];
const arr2 = [15, 88, 1, 5, 7];
const arr3 = [1, 10, 15, 5, 20];
console.log(intersection([arr1, arr2, arr3]));
.as-console-wrapper { max-height: 100% !important; top: auto; }

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.