How do I use .reduce() to take a multi-layered array and return a single layer array from scratch? | Sololearn: Learn to code for FREE!

+1

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

2/3/2019 5:06:37 PM

Jerry Okugbe

+5

Thanks a lot Ben Bright , I will give it a read 👍

+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!

+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!

+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,

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!