简体   繁体   中英

JavaScript: Using Reduce Method to Merge Together Multiple Arrays Into One Array

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?

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])); 

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; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM