+ 1

How do I useĀ .reduce()Ā to take a multi-layered array and return a single layer array from scratch?

3rd Feb 2019, 5:06 PM
Jerry Okugbe
Jerry Okugbe - avatar
5 Answers
+ 5
Thanks a lot Ben Bright , I will give it a read šŸ‘
4th Feb 2019, 8:57 AM
Ipang
+ 4
It all depends on how you want the results to be, but for flat out all arrays into a single layered, you can implement it like this; say we have this 3x3 multi-dimensional array: // array const grades = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]; // reduce const output = grades.reduce((accum, item) => { accum = [...accum, ...item]; return accum; }, []); // result console.log(output) //=> [1, 2, 3, 4, 5, 6, 7, 8, 9] Hope it helps, happy coding!
4th Feb 2019, 1:40 AM
Benneth Yankey
Benneth Yankey - avatar
+ 4
Ipang please read from here it's well explained: // reduce https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce // spread operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax if you still don't get it, send me a chat. Hope it helps, happy coding!
4th Feb 2019, 8:52 AM
Benneth Yankey
Benneth Yankey - avatar
+ 3
Well this is embarrassing šŸ˜, but I don't understand what happens in that section of reduce, the part that's troubling me understanding is with the ... `accum[...accum, ...item]` and the square bracket in the ending ... `},[]);` <- this square bracket Ben Bright ,I need enlightenment with that šŸ˜ Thanks,
4th Feb 2019, 8:41 AM
Ipang
0
//array const arra = [[1,2],[3,4],[4,5,6]]; //newArray const newArr = arra.reduce((a,b)=>{ for(i=0;i<b.length;i++) { a.push(b[i]); // pushing the elements into accumulator } return a; //returning the accumulator for every iteration },[]) console.log(newArr); Hope this helps!
18th Aug 2020, 12:43 PM
San Jith
San Jith - avatar